<?php
namespace app\admin\model;

use app\admin\model\CustomerModel;
use app\admin\model\ShopModel;
use app\admin\model\ShopPerson;
use app\crm\model\Customer;
use app\crm\model\OrderStatistics;
use app\crm\model\ShopPersonAchievementModel;
use app\admin\model\ServiceLog;
use app\crm\model\CustomerLossModel;
use app\crm\model\ReserveandLost;
use think\facade\Db;

class SysModel extends Common

{



    /**

     * @var string

     */

    protected $name = 'admin_sys';



    protected $defaultSoftDelete = 0;



    protected $autoWriteTimestamp = true;



    /**

     * 获取系统首页信息资源

     * @return array

     * @author ran

     * @date 2021-09-23 13:53

     * mailbox 466180170@qq.com

     */

    public function     getAdminSysHomeInfoResource($shopIds,$request): array
    {
		// 月初流失预警顾客
		if($request['startTime']){
			$start_time = $request['startTime'];
		}else{
			$start_time = date("Y-m-01",time());
		}

        $today = date('Y-m-d',time());

        $orderModel = new ShopOrderModel();

        $customerModel = new CustomerModel();

        // $customerLossModel = new CustomerLossModel();

        $model = new ReserveandLost();
		// print_r("阶段1:".time().PHP_EOL);
        $orderCollect =$orderModel->getShopOrderCommonDataCollect($shopIds,$request); //观月业绩
		// print_r("阶段2:".time().PHP_EOL);
        $customerCollect =$customerModel->getCustomerCommonDataCollect($shopIds,$request); //关于进店数据
		// print_r("阶段3:".time().PHP_EOL);
        // exit;
        // 2022-04-27
		$newRequest_t = [];
		// $newRequest_t['cj_time'] = $request['startTime'] ?? '';


        // $request_loss_one = $request;
        // $request_loss_one['shopIds'] = $shopIds;
        // $request_loss_one['is_join_shop'] = '4'; // 流失预警

        // $customerLossOne = $customerLossModel->getDataList($request_loss_one);

        // $request_loss_two = $request;
        // $request_loss_two['shopIds'] = $shopIds;
        // $request_loss_two['is_join_shop'] = '3'; // 流失顾客

        // $customerLossTwo = $customerLossModel->getDataList($request_loss_two);

        $nurse_id = $request['shop_person_id']??0;
        $position_id = $this->getPersonPositionId($nurse_id);
        if(!empty($position_id)){
            $newRequest_t['nurse_id'] = $nurse_id;
        }
        if($shopIds){
            $cj_customerIds = $model->cj_customer($shopIds,$newRequest_t);

        }else{
            $shop_where = [];

            array_push($shop_where,['shop_type','=','2']);

            array_push($shop_where,['type','<>','2']);

            array_push($shop_where,['status','=','1']);

            $shopIds = Db::name('shop')->where($shop_where)->column('shop_id');

            $cj_customerIds = $model->cj_customer($shopIds,$newRequest_t);

        }

        $yj_customerIds = $model->warning_customer($cj_customerIds,$today,'','',''); // 流失预警

        $ls_customerIds = $model->lost_customer($cj_customerIds,$today); // 流失顾客

        $by_customerIds = $model->baoyou_customer($cj_customerIds,$today); // 保有顾客



		$warn_customerIds = $model ->warning_customer('','','back',$shopIds,$start_time); // 月初流失预警顾客

		$over_time = time();

		$back_customerIds = $model ->back_customer($warn_customerIds,$start_time,$over_time);

		//$cjCustomerNum = count($cj_customerIds);                   //成交客户
		/* echo '<pre>';
		print_r($cj_customerIds);

		exit; */

        if($orderCollect['sysDealNumber'] == 0){

            //$orderCollect['sysDealNumber']=1;

        }

        return [

            'sysCurrentPerformance' => round($orderCollect['sysCurrentPerformance'],2),  //当前店铺集合支付总金额

            'sysCompleteNewOrder' => round($orderCollect['sysCompleteNewOrder'],2), //新单

            'sysCompleteSupplement' => round($orderCollect['sysCompleteSupplement'],2),//补单

            'sysNewOrderTurnoverRate' => $customerCollect['sysFinishEnterStore'] == '0' ? '0%' : (round($orderCollect['sysDealNumber']/$customerCollect['sysFinishEnterStore'],2)*100).'%',

            'sysDealNumber' => $orderCollect['sysDealNumber'],  //当前店铺集合支付总订单数量 成交量

			'sysDealNumberEcharts' => $orderCollect['sysDealNumberEcharts'],  // 当前店铺集合支付总订单数量 成交量（疤痕痘痘项目）

            'sysFinishEnterStore' => $customerCollect['sysFinishEnterStore'], // 进店

			'sysFinishEnterStoreEcharts' => $customerCollect['sysFinishEnterStoreEcharts'], // 进店 (疤痕痘痘项目)

            'referralsCout'=>$customerCollect['customerTenureNumber'],

            'sysOnlineStoreEntryRate' => $customerCollect['sysOnlineStoreEntryRate'],

            'customerNumber' => $customerCollect['customerNumber'],

            'customerBirthNumber' => $customerCollect['customerBirthNumber'],

            'customerRevisitedCount' => $customerCollect['customerVisitedNumber'],

            // 'customerTenureNumber' => $customerCollect['tenure'],

            // 'customerDrainNumber' => $customerLossTwo['dataCount'],

            // 'customerWarnNumber' => $customerLossOne['dataCount'],

			'customerCJNumber' => count($cj_customerIds),  //成交客户

            'customerTenureNumber' => count($by_customerIds),

            'customerDrainNumber' => count($ls_customerIds),

            'customerWarnNumber' => count($yj_customerIds),

			'customerRetentionRate' => count($cj_customerIds)>0 ? bcmul(bcdiv(count($by_customerIds),count($cj_customerIds),4),100,2).'%' : '0%',  //保有率

			'back_warn_Rate' => count($warn_customerIds)>0 ? bcmul(bcdiv(count($back_customerIds),count($warn_customerIds),4),100,2).'%' : '0%',  //当月预警回流率

        ];

    }

    //查看护理师岗位id
    public function getPersonPositionId($persion_id){
        $position_id = DB::name('shop_person')->where('id',$persion_id)->value('position_id');
        $position_id = !in_array($position_id,[7,8,10])?$position_id:0;
        return $position_id;
    }

    /**

     * 获取员工业绩

     * @author ran

     * @date 2021-10-22 13:31

     * mailbox 466180170@qq.com

     */

    public function getAdminSysHomePersonAchieveResource($shopIds,$request)
    {


		$start_time = $request['startTime'] ?? '';
		$end_time = $request['endTime'] ?? '';

		if($start_time){

			 $startTime = strtotime($start_time." 00:00:00");
			 $endTime = strtotime($end_time." 23:59:59");

		}else{
			$startTime = strtotime(date('Y-m-01',time()));
			$endTime = strtotime(date('Y-m-t 23:59:59',time()));
		}

		$shopId = $request['shopId'] ?? '';

        /* $personModel = new PersonModel();

        $list =$personModel->getPersonAdminListResourceServiceSys($shopIds,$request,1,10); */



		if($shopIds){

			//echo 'jinru';exit;

			$newRequest['shop_id'] = $shopId;

			$newRequest['startTime'] = $startTime;
			$newRequest['endTime'] = $endTime;
            $where = [];


            if(!empty($request['shop_person_id'])){
                $persion_id = $this->getPersonPositionId($request['shop_person_id']);
                if(!empty($persion_id)){
                    array_push($where,['sp.id','=',$request['shop_person_id']]);
                }
            }


			$staffList = Db::name('shop_person')->alias('sp')

				->join('admin_user au', 'au.shop_person_id = sp.id', 'LEFT')

				->where('au.is_status',0)

                ->where($where)

				->where('sp.shop_id',$shopId)

				->where('sp.position_id','in',[3,4,7,8,9])

				->column('sp.id,sp.name');


			$newRequest['staffList'] = $staffList;

			$rexinMoney = $this->newOrder($newRequest); //新单数据
			$rebuMoney = $this->repairOrder($newRequest); //补单数据

			$experienceMoney = $this->experience($newRequest); //体验成交

			$referralMoney = $this->zhuanNums($newRequest); //体验成交

			$waiLianMoney = $this->waiLianNums($newRequest); //外联人数

			$serviceLogNum = $this->serviceLog($newRequest); //外联人数


			foreach ($staffList as $key => $value) {

				$staffList[$key]['newOrder'] =  $rexinMoney[$value['id']]['newOrder'];

				$staffList[$key]['repairOrder'] =  $rebuMoney[$value['id']]['repairOrder'];

				$staffList[$key]['experience'] =  $experienceMoney[$value['id']]['experience'];

				$staffList[$key]['referral'] =  $referralMoney[$value['id']]['zhuanNums'];

				$staffList[$key]['waiLianNums'] =  $waiLianMoney[$value['id']]['waiLianNums'];

				$staffList[$key]['serviceLog'] =  $serviceLogNum[$value['id']]['serviceLog'];

                $staffList[$key]['serviceCraft'] =  $serviceLogNum[$value['id']]['serviceCraft'];

			}

			return ['list' => $staffList];
		}else{

			return ['list' => ''];

		}
    }



	// 新单业绩
	public function newOrder($request)
	{

	    $start_time = $request['startTime'];

	    $end_time = $request['endTime'];

	    $shop_id = $request['shop_id'];

	    $staff_idss = $request['staffList'];

		$staff_ids = array_column($staff_idss,'id'); //二维数组转换

	    $staff_name = Db::name('shop_person')->where('id','in',$staff_ids)->column('name','id');

	    $list1 = Db::name('shop_refund_order')->where([['shop_id', 'in', $shop_id], ['sale_id', 'in', $staff_ids], ['deal_time', 'between', "$start_time,$end_time"], ['type','=',3], ['status','=',2], ['order_type','=',1], ['refund_type','=','101.02 ']])->group('sale_id')->column('sum(pay_amount) as sum','sale_id');

	    $list2 = Db::name('shop_refund_order')->where([['shop_id', 'in', $shop_id], ['sale_id', 'in', $staff_ids], ['deal_time', 'between', "$start_time,$end_time"], ['type','=',1], ['status','=',2], ['order_type','=',1], ['refund_type','=','101.02 ']])->group('sale_id')->column('sum(pay_amount) as sum','sale_id');

	   $list = [];
	    foreach ($staff_ids as $key => $value) {

	        $shouKuan = $list1[$value] ?? '0.00';

	        $tuiKuan = $list2[$value] ?? '0.00';


			$list[$value]['name'] = $staff_name[$value] ?? '';

			$list[$value]['newOrder'] = bcsub($shouKuan,$tuiKuan,2);

	    }

		return $list;
	}

	// 补单业绩
	public function repairOrder($request){

	    $start_time = $request['startTime'];

	    $end_time = $request['endTime'];

	    $shop_id = $request['shop_id'];

	    $staff_idss = $request['staffList'];

	    $staff_ids = array_column($staff_idss,'id'); //二维数组转换

	    $staff_name = Db::name('shop_person')->where('id','in',$staff_ids)->column('name','id');

	    $list1 = Db::name('shop_refund_order')->where([['shop_id', 'in', $shop_id], ['sale_id', 'in', $staff_ids], ['deal_time', 'between', "$start_time,$end_time"], ['type','=',3], ['status','=',2], ['order_type','=',2], ['refund_type','=','101.02 ']])->group('sale_id')->column('sum(pay_amount) as sum','sale_id');

	    $list2 = Db::name('shop_refund_order')->where([['shop_id', 'in', $shop_id], ['sale_id', 'in', $staff_ids], ['deal_time', 'between', "$start_time,$end_time"], ['type','=',1], ['status','=',2], ['order_type','=',2], ['refund_type','=','101.02 ']])->group('sale_id')->column('sum(pay_amount) as sum','sale_id');

	    $list = [];

	    foreach ($staff_ids as $key => $value) {


	        $shouKuan = $list1[$value] ?? '0.00';

	        $tuiKuan = $list2[$value] ?? '0.00';

			$list[$value]['name'] = $staff_name[$value] ?? '';

			$list[$value]['repairOrder'] = bcsub($shouKuan,$tuiKuan,2);

	    }
	    return $list;
	}

	// 体验成交
	public function experience($request){

	    $start_time = $request['startTime'];

	    $end_time = $request['endTime'];

	    $shop_id = $request['shop_id'];

	    $staff_idss = $request['staffList'];

	    $staff_ids = array_column($staff_idss,'id'); //二维数组转换

	    $staff_name = Db::name('shop_person')->where('id','in',$staff_ids)->column('name','id');

	    $list1 = Db::name('shop_refund_order')->where([['shop_id', 'in', $shop_id], ['is_experience', '=', 1], ['experience_id', 'in', $staff_ids], ['deal_time', 'between', "$start_time,$end_time"], ['type','=',3], ['status','=',2], ['refund_type','=','101.02 ']])->group('experience_id')->column('sum(pay_amount) as sum','experience_id');

	    $list2 = Db::name('shop_refund_order')->where([['shop_id', 'in', $shop_id], ['is_experience', '=', 1], ['experience_id', 'in', $staff_ids], ['deal_time', 'between', "$start_time,$end_time"], ['type','=',1], ['status','=',2], ['refund_type','=','101.02 ']])->group('experience_id')->column('sum(pay_amount) as sum','experience_id');

	    $list = [];

	    foreach ($staff_ids as $key => $value) {


	        $shouKuan = $list1[$value] ?? '0.00';

	        $tuiKuan = $list2[$value] ?? '0.00';

	        $list[$value]['name'] = $staff_name[$value] ?? '';

	        $list[$value]['experience'] = bcsub($shouKuan,$tuiKuan,2);

	    }
	    return $list;
	}

	// 转介绍数
	public function zhuanNums($request){

	    $start_time = $request['startTime'];

	    $end_time = $request['endTime'];

	    $shop_id = $request['shop_id'];

	    $staff_idss = $request['staffList'];

	    $staff_ids = array_column($staff_idss,'id'); //二维数组转换

	    $staff_name = Db::name('shop_person')->where('id','in',$staff_ids)->column('name','id');

	    $list1 = Db::name('shop_refund_order')->where([['shop_id', 'in', $shop_id], ['is_introduction', '=', 1], ['introduction_id', 'in', $staff_ids], ['deal_time', 'between', "$start_time,$end_time"], ['type','=',3], ['status','=',2], ['refund_type','=','101.02 ']])->group('introduction_id')->column('sum(pay_amount) as sum','introduction_id');

	    $list2 = Db::name('shop_refund_order')->where([['shop_id', 'in', $shop_id], ['is_introduction', '=', 1], ['introduction_id', 'in', $staff_ids], ['deal_time', 'between', "$start_time,$end_time"], ['type','=',1], ['status','=',2], ['refund_type','=','101.02 ']])->group('introduction_id')->column('sum(pay_amount) as sum','introduction_id');

	    $list = [];

	    foreach ($staff_ids as $key => $value) {


	        $shouKuan = $list1[$value] ?? '0.00';

	        $tuiKuan = $list2[$value] ?? '0.00';

	        $list[$value]['name'] = $staff_name[$value] ?? '';

	        $list[$value]['zhuanNums'] = bcsub($shouKuan,$tuiKuan,2);

	    }
	    return $list;

	}

	// 外联人数
	public function waiLianNums($request){

	    $start_time = $request['startTime'];

	    $end_time = $request['endTime'];

	    $shop_id = $request['shop_id'];

	    $staff_idss = $request['staffList'];

	    $staff_ids = array_column($staff_idss,'id'); //二维数组转换

	    $staff_name = Db::name('shop_person')->where('id','in',$staff_ids)->column('name','id');

	    $list1 = Db::name('customer')->where([['shop_id', 'in', $shop_id], ['outreach_id', 'in', $staff_ids], ['first_time|second_time', 'between', "$start_time,$end_time"]])->group('outreach_id')->column('count(*) as sum','outreach_id');

	    $list = [];

	    foreach ($staff_ids as $key => $value) {

	        $list[$value]['name'] = $staff_name[$value] ?? '';

	        $list[$value]['waiLianNums'] = $list1[$value] ?? '0';

	    }
	    return $list;
	}

	// 护理次数
	public function serviceLog($request){

	    $start_time = $request['startTime'];

	    $end_time = $request['endTime'];

	    $shop_id = $request['shop_id'];

	    $staff_idss = $request['staffList'];

	    $staff_ids = array_column($staff_idss,'id'); //二维数组转换

	    $staff_name = Db::name('shop_person')->where('id','in',$staff_ids)->column('name','id');

        $public_where =[
            ['shop_id', 'in', $shop_id],
            ['create_time', 'between', "$start_time,$end_time"]
        ];
        $map = [
            ['nurse_id_one', 'in', $staff_ids],
            ['nurse_id_two', '=', 0]
        ];
        $list1 = Db::name('service_log')->where($public_where)->where($map)->group('nurse_id_one')->column('count(*) as sum','nurse_id_one');
        $map = [
            ['nurse_id_one', 'in', $staff_ids],
            ['nurse_id_two', '>', 0]
        ];
        $list2 = Db::name('service_log')->where($public_where)->where($map)->group('nurse_id_one')->column('count(*)*0.5 as sum','nurse_id_one');
        $map = [
            ['nurse_id_one', '>', 0],
            ['nurse_id_two', 'in', $staff_ids]
        ];
        $list3 = Db::name('service_log')->where($public_where)->where($map)->group('nurse_id_two')->column('count(*)*0.5 as sum','nurse_id_two');

        $mz_shop_ids = DB::name('shop')->where('shop_type',1)->column('shop_id');

        $list4 = $list5 = $list6 = $list_five = $list_six =  [];
        if(in_array($shop_id,$mz_shop_ids)){
            $map = [
                ['nurse_id', 'in', $staff_ids],
            ];
            $list4 = DB::name('service_log_control')->where($public_where)->where($map)->field('count(service_item) as sum,nurse_id')->group('nurse_id')->select()->toArray();
            $list4 = array_column($list4,null,'nurse_id');


            $list5 = Db::name('service_log')->where($public_where)->whereIn('nurse_one',$staff_ids)->field('nurse_one_project,nurse_one')->select()->toArray();

            if(!empty($list5)){
                $list_five = [];
                foreach($list5 as $kk=>$vv){
                    if(isset($list_five[$vv['nurse_one']])){
                        $list_five[$vv['nurse_one']][]= count(explode(',',$vv['nurse_one_project']));
                    }else{
                        $list_five[$vv['nurse_one']][] = count(explode(',',$vv['nurse_one_project']));
                    }
                }
            }

            $map = [
                ['nurse_two', 'in', $staff_ids],
            ];
            $list6 = Db::name('service_log')->where($public_where)->where($map)->field('nurse_two_project,nurse_two')->select()->toArray();
            if(!empty($list6)){
                $list_six = [];
                foreach($list6 as $kk=>$vv){
                    if(isset($list_six[$vv['nurse_two']])){
                        $list_six[$vv['nurse_two']][]= count(explode(',',$vv['nurse_two_project']));
                    }else{
                        $list_six[$vv['nurse_two']][] = count(explode(',',$vv['nurse_two_project']));
                    }
                }
            }

        }

	    $list = [];

	    foreach ($staff_ids as $key => $value) {

	        $num1 = $list1[$value] ?? '0';

	        $num2 = $list2[$value] ?? '0';

	        $num3 = $list3[$value] ?? '0';

            $num4 = $list4[$value] ?? '0';

            $num5 = isset($list_five[$value])?array_sum($list_five[$value]):0;

            $num6 = isset($list_six[$value])?array_sum($list_six[$value]):0;

            $num_five_six = bcadd($num5,$num6);

            $hezuo = bcadd($num2,$num3);

			$list[$value]['name'] = $staff_name[$value] ?? '';
			$list[$value]['serviceLog'] = bcadd($num1,$hezuo);
            $list[$value]['serviceCraft'] = bcadd($num_five_six,$num4);

	    }



	    return $list;
	}
    /**

     * 获取系统信息

     * @author ran

     * @date 2021-10-22 13:31

     * mailbox 466180170@qq.com

     */

    public function getAdminSysServerInfoResource()

    {

        $serverInfo = $this->where('name', 'system')->value('value');

        return json_decode($serverInfo, true);

    }



    /**

     * 获取系统登录日志

     * @author ran

     * @date 2021-10-22 13:31

     * mailbox 466180170@qq.com

     */

    public function getAdminSysLoginLogResource()

    {

        $record = new RecordModel();

        return $record->page(1, 3)->select();

    }



    /**

     * 获取系统账户信息

     * @author ran

     * @date 2021-10-22 13:31

     * mailbox 466180170@qq.com

     */

    public function getAdminSysUserResource($userId)

    {

        $field = ['id', 'username', 'email'];

        $user = new UserModel();

        return $user->field($field)->where('id', $userId)->find();

    }

    /**

     * 获取系统账户信息

     * @author ran

     * @date 2021-10-22 13:31

     * mailbox 466180170@qq.com

     */

    public function getAdminSysUserInfoResource($userId)

    {

        $field = ['id', 'username', 'email','img','thumb_img'];

        $user = new UserModel();

        return $user->field($field)->where('id', $userId)->find();

    }



    /**

     * 更新系统账户信息

     * @author ran

     * @date 2021-10-22 13:31

     * mailbox 466180170@qq.com

     */

    public function updateAdminSysUserResource($request,$userId)

    {

        $field = ['id', 'salt', 'username', 'password', 'email'];

        $user = new UserModel();

        $info = $user->field($field)->where('id', $userId)->find();

        $encryOldPass = user_md5($request['oldPass'], $info['salt'], $info['username']);

        if ($encryOldPass != $info['password']) {

            $this->error = '您输入原始密码不正确';

            return false;

        }

        if ($request['newPass'] != $request['confirmPass']) {

            $this->error = '您两次输入的密码不一致,请检查';

            return false;

        }

        $data = [

            'id' => $info['id'],

            'email' => $request['email']??'',

            'img' => $request['img']??'',

            'thumb_img' => $request['thumb_img']??'',

            'password' => user_md5($request['newPass'], $info['salt'], $info['username']),

        ];

        $user->update($data);

        return true;

    }


    //综合等级判定
    public function ComprehensiveGrade($holding_num){
        $level = '';
        if($holding_num >200){
            $level = 'A';
        }elseif($holding_num >=150 && $holding_num <=200){
            $level = 'B';
        }elseif($holding_num<150){
            $level = 'C';
        }
        return $level;
    }

    //公共的搜索条件
    public function getPublicSearch($request){
        $shop_type = isset($request['shop_type'])?$request['shop_type'] :2; //门店类型  1 门诊 2门店
        $market_id = isset($request['market_id'])?$request['market_id'] :0; //市场的id
        $shop_id = isset($request['shop_id'])?$request['shop_id'] :0; //门店的id
        $start_time1 = isset($request['start_time']) ?$request['start_time'] :'';// 时间段搜索开始时间
        $end_time1 = isset($request['end_time']) ?$request['end_time'] :'';//时间端搜索结束时间
        $time_type = isset($request['time_type'])?$request['time_type']:1; // 1 当月
        switch ($time_type){
            case 1:
                $start_time = strtotime(date('Y-m-01'));
                $end_time   = time();
                break;
        }
        if(!empty($start_time1) && !empty($end_time1)){
            $start_time = strtotime($start_time1);
            $end_time   = strtotime($end_time1);
        }
        return [$shop_type,$market_id,$shop_id,$time_type,$start_time,$end_time];
    }


    /**
     * 客户数量板块-倒三角
     * @author ran
     * @date 2021-10-22 13:31
     * mailbox 466180170@qq.com
     */
    public function getPyramidInfo($shopIds,$request){

        list($shop_type,$market_id,$shop_id,$time_type,$start_time,$end_time) = $this->getPublicSearch($request);
        $shop_where =[
            ['shop_type','=',$shop_type],
            ['type','<>',2],
            ['status','=',1]
        ];
        $shop_total_where = [
            ['shop_type','=',$shop_type]
        ];
        if($market_id>0){
            array_push($shop_where,['market_id','=',$market_id]);
            array_push($shop_total_where,['market_id','=',$market_id]);
        }
        $shop_ids = DB::name('shop')->where($shop_where)->column('shop_id');

        $public_where = [];
        if($shopIds){
            $shop_ids = $shopIds;
        }
        array_push($public_where,['shop_id','in',$shop_ids]);
        array_push($shop_total_where,['shop_id','in',$shop_ids]);

        if($shop_id>0){
            array_push($public_where,['shop_id','=',$shop_id]);
            array_push($shop_total_where,['shop_id','=',$shop_id]);

        }
        $map = [];
        array_push($map,['create_time','between',"$start_time,$end_time"]);
        //客户档案量
        $customerIds = CustomerModel::where($public_where)->where($map)->column('id');
        $customerCount = count($customerIds);

        $where = [];
        array_push($where,['first_time|second_time','between',"$start_time,$end_time"]);
        array_push($where,['first_time','>',0]);
        //客户进店数量
        $customerEntershopCount = CustomerModel::where($public_where)->where($where)->count();

        //客户成交数量
        $cj_map = [
            ['cj_money','>',0],
            ['cj_time','between',"$start_time,$end_time"]
        ];
        //成交数
        $cj_customerIds = CustomerModel::where($public_where)->where($cj_map)->column('id');
        $cj_customerCount = count($cj_customerIds);

        $model = new ReserveandLost();
        $today = date('Y-m-d');
        $yesterday  =  date('Ymd', strtotime("-1 day", strtotime($today)));

        array_push($shop_total_where,['date','=',$yesterday]);

        $by_customerCount = DB::name('shop_total_log')->where($shop_total_where)->field('sum(by_total_num) as count')->find();
        $by_customerCount = $by_customerCount['count'];



        //进店率
        $enter_rate = $customerCount > 0 ? bcmul(bcdiv($customerEntershopCount,$customerCount,4),100,2).'%' : '0%';
        //成交率
        $cj_rate    = $customerEntershopCount >0 ? bcmul(bcdiv($cj_customerCount,$customerEntershopCount,4),100,2).'%' : '0%';
        //保有率
        $by_rate    = 0;

        $return=[
            'count'=>[
                'customer_count'=>$customerCount,
                'inshop_count'=>$customerEntershopCount,
                'cj_count'=>$cj_customerCount,
                'by_count'=>$by_customerCount
            ],
            'rate'=>['enter_rate'=>$enter_rate,'cj_rate'=>$cj_rate,'by_rate'=>$by_rate],
            'by_count'=>$by_customerCount,
            'level'=> $this->level($by_customerCount)
        ];
        return $return;
    }

    public function level($by_count){
        $level = 'C';
        if($by_count >=200){
            $level = 'A';
        } else if($by_count >= 150 &&  $by_count <= 200 ){
            $level = 'B';
        }
        return $level;
    }

    //员工价值板块
    public function getPersonInfo($shop_ids,$request){
        list($shop_type,$market_id,$shop_id,$time_type,$start_time,$end_time) = $this->getPublicSearch($request);

        $return =[
            'customer_cj_count'=> 0,
            'customer_by'=>0,
            'customer_ls'=> 0,
            'replenishment'=>0,
            'care_amount_dayavg'=> 0,
            'care_customer_dayavg'=>0,
        ];
        if(!empty($shop_ids)){
            $shop_id = $shop_ids[0];
        }else{
            $map=[
                ['shop_type','=',$shop_type],
                ['status','=',1],
                ['type','<>',2]
            ];
            if(empty($shop_id)){
                $shop_id = DB::name('shop')->where($map)->value('shop_id');
            }
        }
        if(empty($shop_id)){
            return $return;
        }
        $customerCount = Customer::where('shop_id',$shop_id)->count(); //顾客数

        $today = date('Y-m-d',time());
        $reserveAndLostModel = new ReserveandLost();
        //保有顾客数、流失顾客数、补单业绩、护理量 日均护理量 日均客户数
        $by_customer_count = $ls_customer_count = $bd_amount_sum = $hl_count = $day_avg_hj = $day_avg_customer= $customer_cj_count = 0;
        if($customerCount>0){
            $map = [
                ['shop_id','=',$shop_id],
                ['cj_time','<=',$end_time],
                ['cj_time','<>',0],
                ['cj_money','<>',0],
            ];
            $cj_customer =  Customer::where($map)->column('id');
            $lost_caseIds = $reserveAndLostModel->lost_case($cj_customer,$today);
            $cj_customerIds = array_diff($cj_customer,$lost_caseIds); //最终成交的顾客id
            $customer_cj_count = count($cj_customerIds);

            if(!empty($cj_customerIds)){
                $by_customerIds = $reserveAndLostModel->baoyou_customer($cj_customerIds,$today); // 保有顾客 id
                $by_customer_count = count($by_customerIds); //保有顾客数
                $ls_customerIds = $reserveAndLostModel->lost_customer($cj_customerIds,$today); // 流失顾客 id组
                $ls_customer_count = count($ls_customerIds); // 流失顾客数
            }
            //补单业绩
            $shop_info = ShopModel::where('shop_id',$shop_id)->field('shop_type,shop_id,market_id')->find();
            //补单业绩
            $bd_amount_sum =  $this->supplePerson($shop_info,$start_time,$end_time);
            //员工的id
            $personids =  ShopPerson::where([['shop_id', '=', $shop_id],['status','<>',3],['name','<>','虚拟员工核销专用']])->column('id');
            $map = [
                ['nurse_id_one', 'in', $personids],
                ['nurse_id_two','=','0'],
                ['create_time', 'between', "$start_time,$end_time"],
                ['category_id','in',[1,8,10,11,4,12]],
                ['is_cancel','=',0]
            ];
            $service1 = ServiceLog::where($map)->count();
            $map1= [
                ['nurse_id_one', 'in', $personids],
                ['nurse_id_two','in',$personids],
                ['create_time', 'between', "$start_time,$end_time"],
                ['category_id','in',[1,8,10,11,4,12]],
                ['is_cancel','=',0]
            ];
            $service2 = ServiceLog::where($map1)->count();

            $map2 = [
                ['nurse_id_one', '=', '0'],
                ['nurse_id_two','in',$personids],
                ['create_time', 'between', "$start_time,$end_time"],
                ['category_id','in',[1,8,10,11,4,12]],
                ['is_cancel','=',0]];
            $service3 = ServiceLog::where($map2)->count();
            $hl_count = $service1+$service2+$service3;
            $searchdaydiff = $this->getDateDiff($start_time,$end_time);
            $day_avg_hj =  $searchdaydiff > 0 ? bcdiv($hl_count,$searchdaydiff) :0; //日均护理数
            $day_avg_customer_map = [
                ['is_cancel','=',0],
                ['create_time', 'between', "$start_time,$end_time"],
                ['shop_id','=',$shop_info['shop_id']]
            ];
            $customerIds = ServiceLog::where($day_avg_customer_map)->distinct(true)->field('customer_id')->select()->toArray();
            $customerIds = count(array_column($customerIds,'customer_id')); //客户数
            $day_avg_customer = $searchdaydiff>0? bcdiv($customerIds,$searchdaydiff):0; //日均客户数
        }
        $return =[
            'customer_cj_count'=> $customer_cj_count,
            'customer_by'=>$by_customer_count,
            'customer_ls'=> $ls_customer_count,
            'replenishment'=>$bd_amount_sum,
            'care_amount_dayavg'=> $day_avg_hj,
            'care_customer_dayavg'=>$day_avg_customer,
        ];
        return $return;
    }
    //获取两个日期相差天数
    public function getDateDiff($begin_time,$end_time){
        // 使用strtotime和date_diff计算天数差
        $daysDiff = (int)(($end_time - $begin_time) / 85399);
        return $daysDiff;
    }
    //客户价值-ABCD类客户(各类客户)
    public function getCustomerValue($shopIds,$request){

        list($shop_type,$market_id,$shop_id,$time_type,$start_time,$end_time) = $this->getPublicSearch($request);

        $shop_total_where = [
            ['shop_type','=',$shop_type]
        ];
        if($market_id>0){
            array_push($shop_total_where,['market_id','=',$market_id]);
        }
        if($shopIds){
            $shop_ids = $shopIds;
            array_push($shop_total_where,['shop_id','in',$shop_ids]);
        }
        if($shop_id>0){
            array_push($shop_total_where,['shop_id','=',$shop_id]);
        }
        $today = date('Y-m-d');
        $yesterday  =  date('Ymd', strtotime("-1 day", strtotime($today)));
        array_push($shop_total_where,['date','=',$yesterday]);

        $by_total_customer_id = DB::name('shop_total_log')->where($shop_total_where)->column('by_total_customer_id');
        $customer_id = [];
        foreach($by_total_customer_id as $key=>$v){
            if(!empty($v)){
                $arr = explode(',',$v);
                $customer_id = array_merge($arr,$customer_id);
            }
        }
        $customer_data = [];
        if(!empty($customer_id)){
            $customer_data = Customer::whereIn('id',$customer_id)->group('member_classification')->column('count(id) as sum','member_classification');
        }
        $AcustomerCount =  isset($customer_data[73])?$customer_data[73]:0;
        $BcustomerCount =  isset($customer_data[72])?$customer_data[72]:0;
        $CcustomerCount =  isset($customer_data[71])?$customer_data[71]:0;
        $DcustomerCount =  isset($customer_data[70])?$customer_data[70]:0;

        return [
            ['name'=>'A类','value'=>$AcustomerCount],
            ['name'=>'B类','value'=>$BcustomerCount],
            ['name'=>'C类','value'=>$CcustomerCount],
            ['name'=>'D类','value'=>$DcustomerCount],
        ];


    }
    //客户价值-年度消费金额
    public function getYearCustomerPay($shopIds,$request){
        list($shop_type,$market_id,$shop_id,$time_type,$start_time,$end_time) = $this->getPublicSearch($request);

        $shop_where = $map =  [];

        array_push($shop_where,['type','<>','2']);
        array_push($shop_where,['status','=','1']);
        if(!empty($market_id)){
            array_push($shop_where,['market_id','=',$market_id]);
        }
        if(!empty($shop_id)){
            array_push($shop_where,['shop_id','=',$shop_id]);
        }
        if(!empty($shopIds)){
            array_push($shop_where,['shop_id','in',$shopIds]);
        }
        if($shop_type == 1){
            $mz_shopIds = ShopModel::where($shop_where)->column('shop_id'); //门诊
            $shopIds = ShopModel::where(['status'=>1,'shop_type'=>2])->column('shop_id'); //门店
            $map =[
                ['shop_id','in',$mz_shopIds]
            ];
        }else{
            $shopIds = ShopModel::where($shop_where)->column('shop_id'); //门店
            $mz_shopIds = ShopModel::where(['status'=>1,'shop_type'=>1])->column('shop_id'); //门诊
            $map =[
                ['shop_id','in',$shopIds]
            ];
        }
        $start_time = date('Y')."0101";
        $end_time = date('Ymd');

        $customer_id = Db::name('customer')->where('cj_time','>',0)->where('cj_money','>=',500)->where($map)->column('id');

        array_push($map,['date','between',"$start_time,$end_time"]);
        $where = [];
        array_push($where,['date','between',"$start_time,$end_time"]);

        $c_id  = Db::name('customer_consumption_log')->where($map)->column('customer_id');

        $now_customer_id = array_intersect($c_id,$customer_id);

        $c_phone  = Db::name('customer_consumption_log')->where($map)->whereIn('customer_id',$now_customer_id)->column('customer_phone');

        $customer = Db::name('customer_consumption_log')
            ->where($where)
            ->whereIn('customer_phone',$c_phone)
            ->field('customer_phone,sum(consumption_sum) as consumption_sum')
            ->group('customer_phone')
            ->select()->toArray(); //门店的客户数据

        $a = $b = $c = $d =  [];
        foreach($customer as $k=>$v){
//            $shop_expenditure = $this->getCustomerExpenditure([$v['id']],$start_time,$end_time);
//            if($shop_type == 1){
//                $mz_customer_id = Customer::whereIn('shop_id',$shopIds)->where('telephone',$v['telephone'])->column('id'); //门诊的的客户数据
//            }else{
//                $mz_customer_id = Customer::whereIn('shop_id',$mz_shopIds)->where('telephone',$v['telephone'])->column('id'); //门店的的客户数据
//            }
//            $mz_expenditure = 0;
//            if(!empty($mz_customer_id)){
//                $mz_expenditure = $this->getCustomerExpenditure($mz_customer_id,$start_time,$end_time);
//            }
//            $expenditure = bcadd($shop_expenditure,$mz_expenditure,2);
            $expenditure = $v['consumption_sum'];
            if($expenditure>50000){
                array_push($a,$v['customer_phone']);
            }else if($expenditure <=50000 && $expenditure >=15000){
                array_push($b,$v['customer_phone']);
            }else if($expenditure <15000 && $expenditure >=5000){
                array_push($c,$v['customer_phone']);
            }else if($expenditure <5000){
                array_push($d,$v['customer_phone']);
            }
        }

        $a =count($a);
        $b = count($b);
        $c = count($c);
        $d = count($d);

        return ['consumption'=>[$a,$b,$c,$d]];
    }
    //客户价值及门店级别
    public function customerValue($shopIds,$request){
        list($shop_type,$market_id,$shop_id,$time_type,$start_time,$end_time) = $this->getPublicSearch($request);

        $begin_time = date('Y')."0101";
        $last_today_time = date('Ymd',strtotime('-1 day'));

        $map = $shop_map = $shop_total_where =  [];

        $where = [
            ['date',"between","$begin_time,$last_today_time"],
            ['shop_type','=',$shop_type],
        ];

        array_push($shop_map,['shop_type','=',$shop_type]);
        array_push($shop_map,['status','=',1]);
        array_push($shop_map,['type','<>',2]);

        $shop_total_where  = [
            ['shop_type','=',$shop_type],
        ];

        if(!empty($shopIds)){
            array_push($shop_map,['shop_id','in',$shopIds]);
            array_push($where,['shop_id','in',$shopIds]);
            array_push($shop_total_where,['shop_id','in',$shopIds]);
        }

        if(!empty($market_id)){
            array_push($shop_map,['market_id','=',$market_id]);
            array_push($where,['market_id','=',$market_id]);
            array_push($shop_total_where,['market_id','=',$market_id]);
        }

        if(!empty($shop_id)){
            array_push($shop_map,['shop_id','=',$shop_id]);
            array_push($where,['shop_id','=',$shop_id]);
            array_push($shop_total_where,['shop_id','=',$shop_id]);
        }

        $shopData  = DB::name('shop')->where($shop_map)->field('shop_id,shop_type,market_id')->select()->toArray();

        $shopIds  = array_column($shopData,'shop_id');


        $amount_sum = $amount_avg = 0;


        $start_time =  strtotime($begin_time);
        $end_time  = time(); //截止到目前

        array_push($map,['cj_time','between',"$start_time,$end_time"]);
        array_push($map,['cj_money','>=',500]);
        array_push($map,['shop_id','in',$shopIds]);
        //顾客成交人数
        $customerBargain = DB::name('customer')->where($map)->field('count(DISTINCT(id)) as sum')->find();

        if($customerBargain['sum'] >0){
            //查询除当天的业绩

            $data = DB::name('shop_performance_log')->where($where)->field("sum(xd_amount) as xd_amount,sum(bd_amount) as bd_amount")->find();



            $last_day_end_amount_sum = bcadd($data['xd_amount'],$data['bd_amount'],2); //除当天的业绩

            //九月份新的计算规则 begin
            $shopModel = new ShopModel();

            $start_time = strtotime(date('Y-m-d'));

            $mzXDMoneyAllOne = $shopModel->outpatientPerform($shopIds,1,$start_time,$end_time); //门诊新单业绩

            $mzBDMoneyAllTwo = $shopModel->outpatientPerform($shopIds,2,$start_time,$end_time); //门诊补单业绩

            $shopXDMoneyAllOne = $shopModel->shopPerform($shopIds,1,$start_time,$end_time);  //门店新单业绩

            $shopBDMoneyAllTwo = $shopModel->shopPerform($shopIds,2,$start_time,$end_time);  //门店补单业绩
            //九月份新的计算规则 end

            $xd = $bd = [];
            foreach ($shopData as $key=>$val) {
                //从9月份开始用新的计算规则
                if ($val['shop_type'] == 1) {
                    //门诊
                    $SepnewsXDMoney = empty($mzXDMoneyAllOne[$val['shop_id']]) ? 0 : $mzXDMoneyAllOne[$val['shop_id']];
                    $SepbudanMoney = empty($mzBDMoneyAllTwo[$val['shop_id']]) ? 0 : $mzBDMoneyAllTwo[$val['shop_id']];

                } else {
                    //门店
                    $SepnewsXDMoney = empty($shopXDMoneyAllOne[$val['shop_id']]) ? 0 : $shopXDMoneyAllOne[$val['shop_id']];
                    $SepbudanMoney = empty($shopBDMoneyAllTwo[$val['shop_id']]) ? 0 : $shopBDMoneyAllTwo[$val['shop_id']];
                }
                array_push($xd,$SepnewsXDMoney);
                array_push($bd,$SepbudanMoney);
            }
            $xd = array_sum($xd);
            $bd = array_sum($bd);
            $sepzongyeji = bcadd($xd,$bd,2); //所有门店当天的业绩
            $amount_sum = bcadd($sepzongyeji,$last_day_end_amount_sum, 2);


            $amount_avg = bcdiv($amount_sum,$customerBargain['sum'],2);
        }



        //累计保有客户数
        $today = date('Y-m-d');
        $yesterday  =  date('Ymd', strtotime("-1 day", strtotime($today)));
        array_push($shop_total_where,['date','=',$yesterday]);
        $by_customerCount = DB::name('shop_total_log')->where($shop_total_where)->field('sum(by_total_num) as count')->find();
        $by_customer_num = $by_customerCount['count'];

        //绝对价值
        $abs_price =  $by_customer_num>0 ? bcdiv($amount_sum,$by_customer_num,2):0;





        $level = $this->JudgingLevel($amount_avg);

        return ['amount_sum'=>$amount_sum,'shop_level'=>$level,'amount_avg'=>$amount_avg,'cj_count'=>$customerBargain['sum'],'abs_price'=>$abs_price,'by_customer_num'=>$by_customer_num];
    }
    //门店评级
    public function JudgingLevel($moeny){
        $level = '';
        if($moeny<12000){
            $level = 'C-';
        }else if($moeny>=12000 && $moeny<15000){
            $level = 'C';
        }else if($moeny>=15000 && $moeny<20000){
            $level = 'B';
        }else if($moeny>=20000 && $moeny<25000){
            $level = 'A';
        }else if($moeny>=25000){
            $level = 'A+';
        }
        return $level;
    }
    //指标一-进店数量
    public function enterShop($shopId,$request){
        list($shop_type,$market_id,$shop_id,$time_type,$start_time,$end_time) = $this->getPublicSearch($request);

        $map = $lastmap = [];
        $shopIds = ShopModel::where('shop_type',$shop_type)->where('status',1)->column('shop_id');
        if(!empty($shopId)){
            $shopId = array_intersect($shopIds,$shopId);
            array_push($map,['shop_id','in',$shopId]);
            array_push($lastmap,['shop_id','in',$shopId]);
        }

        if(!empty($market_id)){
            $shopId = ShopModel::where('market_id',$market_id)->where('shop_type',$shop_type)->where('status',1)->column('shop_id');
            array_push($map,['shop_id','in',$shopId]);
            array_push($lastmap,['shop_id','in',$shopId]);
        }
        if(!empty($shop_id)){
            array_push($map,['shop_id','=',$shop_id]);
            array_push($lastmap,['shop_id','=',$shop_id]);
        }
        $begin_time = $start_time;
        $last_begin_time = $this->getlastYear($begin_time);
        $last_end_time = $this->getlastYear($end_time);
        array_push($map,['first_time|second_time','between',"$begin_time,$end_time"]);
        array_push($lastmap,['first_time|second_time','between',"$last_begin_time,$last_end_time"]);
        $source_id = $this->getCustomerSource();

        $where = [
            ['source_id', 'in', $source_id[1]]
        ];
        //网络进店
        $internetCount = CustomerModel::where($map)->where($where)->count();
        $lastInternetCount = CustomerModel::where($lastmap)->where($where)->count();

        $where = [
            ['source_id' ,'=', $source_id[2]]
        ];
        //转介绍
        $transfer_introduction_count = CustomerModel::where($map)->where($where)->count();
        $last_transfer_introduction_count = CustomerModel::where($lastmap)->where($where)->count();
        $where = [
            ['source_id', 'in', $source_id[3]]
        ];
        //外联  店转不计算门店进店统计
        $outreach_count =  CustomerModel::where($map)->where($where)->count();
        $last_outreach_count = CustomerModel::where($lastmap)->where($where)->count();
        $year = date('Y');
        $lastYear = bcsub($year,1,0);

          $return = [
            'year'=>[$lastYear,$year],
            'one'=>[$lastInternetCount,$last_transfer_introduction_count,$last_outreach_count],
            'two'=>[$internetCount,$transfer_introduction_count,$outreach_count],
          ];
        return $return;
    }
    //疤痕/痘痘/皮肤数据分析
    public function classEnterShop($shopId,$request){
        list($shop_type,$market_id,$shop_id,$time_type,$start_time,$end_time) = $this->getPublicSearch($request);
        $map = $lastmap = [];
        $shopIds = ShopModel::where('shop_type',$shop_type)->where('status',1)->column('shop_id');
        if(!empty($shopId)){
            $shopId = array_intersect($shopIds,$shopId);
            array_push($map,['a.shop_id','in',$shopId]);
            array_push($lastmap,['a.shop_id','in',$shopId]);
        }
        if(!empty($market_id)){
            $shopId = ShopModel::where('market_id',$market_id)->where('shop_type',$shop_type)->where('status',1)->column('shop_id');
            array_push($map,['a.shop_id','in',$shopId]);
            array_push($lastmap,['a.shop_id','in',$shopId]);
        }
        if(!empty($shop_id)){
            array_push($map,['a.shop_id','=',$shop_id]);
            array_push($lastmap,['a.shop_id','=',$shop_id]);
        }
        $begin_time = $start_time;

        $last_begin_time = $this->getlastYear($begin_time);
        $last_end_time = $this->getlastYear($end_time);

        array_push($map,['a.first_time|a.second_time','between',"$begin_time,$end_time"]);
        array_push($lastmap,['a.first_time|a.second_time','between',"$last_begin_time,$last_end_time"]);
        if(in_array($request['type'],[1,2,3])){
            $source_id = $this->getCustomerSource();
            switch ($request['type']){
                case 1:
                    $where = [
                        ['source_id', 'in', $source_id[1]]
                    ];
                    break;
                case 2:
                    $where = [
                        ['source_id' ,'=', $source_id[2]]
                    ];
                    break;
                case 3:
                    $where = [
                        ['source_id', 'in', $source_id[3]]
                    ];
                    break;
            }
        }
        $getXData = $this->getXData();
        $bh = $getXData['bh'];
        $dd = $getXData['dd'];
        $xm = $getXData['xm'];
        /*********疤痕 begin******/
        $map1= $lastmap1 =  [];
        array_push($map1,['b.customer_setting_id_type','in',$bh]);
        array_push($lastmap1,['b.customer_setting_id_type','in',$bh]);


        $bh_enter_shop = Customer::alias('a')
            ->join('customer_scar b', 'a.id = b.customer_id', 'left')
            ->field('count(distinct a.id) as num')->where($map)->where($map1)->where($where)->find();

        $last_bh_enter_shop = Customer::alias('a')
            ->join('customer_scar b', 'a.id = b.customer_id', 'left')
            ->field('count(distinct a.id) as num')->where($lastmap)->where($lastmap1)->where($where)->find();
        /*********疤痕 end******/
        $map1= $lastmap1 =  [];
        array_push($map1,['b.customer_setting_id_type','in',$dd]);
        array_push($lastmap1,['b.customer_setting_id_type','in',$dd]);

        $dd_enter_shop = Customer::alias('a')
            ->join('customer_scar b', 'a.id = b.customer_id', 'left')
            ->field('count(distinct a.id) as num')->where($map)->where($map1)->where($where)->find();

        $last_dd_enter_shop = Customer::alias('a')
            ->join('customer_scar b', 'a.id = b.customer_id', 'left')
            ->field('count(distinct a.id) as num')->where($lastmap)->where($lastmap1)->where($where)->find();

        $map1= $lastmap1 =  [];
        array_push($map1,['b.customer_setting_id_type','in',$xm]);
        array_push($lastmap1,['b.customer_setting_id_type','in',$xm]);

        $xm_enter_shop = Customer::alias('a')
            ->join('customer_scar b', 'a.id = b.customer_id', 'left')
            ->field('count(distinct a.id) as num')->where($map)->where($map1)->where($where)->find();

        $last_xm_enter_shop = Customer::alias('a')
            ->join('customer_scar b', 'a.id = b.customer_id', 'left')
            ->field('count(distinct a.id) as num')->where($lastmap)->where($lastmap1)->where($where)->find();

        $year = date('Y');
        $lastYear = bcsub($year,1,0);

        $return = [
            'year'=>[$lastYear,$year],
            'one'=>[$last_bh_enter_shop['num'],$last_dd_enter_shop['num'],$last_xm_enter_shop['num']],
            'two'=>[$bh_enter_shop['num'],$dd_enter_shop['num'],$xm_enter_shop['num']],
        ];
        return $return;
    }
    //指标二-成交个数
    public function getPaySuccess($shopId,$request){

        list($shop_type,$market_id,$shop_id,$time_type,$start_time,$end_time) = $this->getPublicSearch($request);
        $map = $lastmap = $cj_one = $cj_two = $cj_one_rate =  $cj_two_rate = [];

        $shop_where = [
            ['shop_type','=',$shop_type],
            ['type','<>',2],
            ['status','=',1]
        ];
        $shop_ids = DB::name('shop')->where($shop_where)->column('shop_id');
        array_push($map,['shop_id','in',$shop_ids]);
        array_push($lastmap,['shop_id','in',$shop_ids]);

        if(!empty($shopId)){
            array_push($map,['shop_id','in',$shopId]);
            array_push($lastmap,['shop_id','in',$shopId]);
        }
        if(!empty($market_id)){
            $shopId = ShopModel::where('market_id',$market_id)->where('status',1)->column('shop_id');
            array_push($map,['shop_id','in',$shopId]);
            array_push($lastmap,['shop_id','in',$shopId]);
        }

        if(!empty($shop_id)){
            array_push($map,['shop_id','=',$shop_id]);
            array_push($lastmap,['shop_id','=',$shop_id]);
        }



        $year = date('Y');
        $month = date('m');
        $lastYear = bcsub($year,1,0);

        for($i = 1; $i<=12;$i++){
            if($i<=$month){
                $begin_time = strtotime(date("Y-".$i));
                $end_time = strtotime(date('Y-'.$i."-t 23:59:59"));


                $last_begin_time = $this->getlastYear($begin_time);
                $last_end_time = $this->getlastYear($end_time);

                $where = $lastwhere = [];
                array_push($where,['cj_money','>=',500]);
                array_push($lastmap,['cj_money','>=',500]);
                array_push($where,['cj_time','between',"$begin_time,$end_time"]);
                array_push($lastwhere,['cj_time','between',"$last_begin_time,$last_end_time"]);

                $make_bargain = DB::name('customer')->where($map)->where($where)->count(); //月份成交

                $last_make_bargain =DB::name('customer')->where($map)->where($lastwhere)->count();//去年月份成交

                array_push($cj_one,$last_make_bargain);
                array_push($cj_two,$make_bargain);

                $where = $lastwhere = [];
                array_push($where,['first_time|second_time','between',"$begin_time,$end_time"]);
                array_push($lastwhere,['first_time|second_time','between',"$last_begin_time,$last_end_time"]);

                $enter_shop = DB::name('customer')->where($map)->where($where)->count(); //月份进店

                $last_enter_shop = DB::name('customer')->where($map)->where($lastwhere)->count();//去年月份进店

                $make_bargain_rate = $enter_shop >0  ? bcmul(bcdiv($make_bargain,$enter_shop,4),100,2):0;
                $last_make_bargain_rate =  $last_enter_shop > 0 ? bcmul(bcdiv($last_make_bargain,$last_enter_shop,4),100,2):0;

                array_push($cj_one_rate,$last_make_bargain_rate);
                array_push($cj_two_rate,$make_bargain_rate);
            }else{
                array_push($cj_one,0);
                array_push($cj_two,0);
                array_push($cj_one_rate,0);
                array_push($cj_two_rate,0);
            }
        }

        $return = [
            'cj_one'=>$cj_one,
            'cj_two'=>$cj_two,
            'cj_one_rate'=>$cj_one_rate,
            'cj_two_rate'=>$cj_two_rate,
            'year'=>[$lastYear,$year]
        ];
        return $return;
    }


    //获取去年时间戳
    public function getlastYear($currentDate){
        return  strtotime('-1 year',$currentDate);
    }
    //获取客户来源
    public function getCustomerSource(){
        // 1网络  2转介绍  3 外联
        return [
            '1'=> [43,44,50,51,52,54,55,56,118,584,609,597,654],
            '2'=> 49,
            '3'=> [46,47,48,583,608]
        ];
    }
    //获取X图 数据
    public function getXData(){
        return [
            'bh'=>[1, 2, 3, 4, 5, 6, 7, 8,655,656],
            'dd'=>[10],
            'xm'=>[9,11,12]
        ];
    }
    //获取进店的数据
    public function enshopCustomerData($whereOr,$type){
        $baseWhere = [];
        if(in_array($type,[1,2,3])){
            switch ($type){
                case 1:
                    array_push($baseWhere,['source_id','in',$this->getCustomerSource[1]]);break;
                case 2:
                    array_push($baseWhere,['source_id','in',$this->getCustomerSource[2]]);break;
                case 3:
                    array_push($baseWhere,['source_id','in',$this->getCustomerSource[3]]);break;
            }
        }
        $getXData = $this->getXData();
        $bh = $getXData['bh'];
        $dd = $getXData['dd'];
        $xm = $getXData['xm'];

        $where = array_merge($baseWhere, [['b.customer_setting_id_type', 'in', $bh]]);
        //疤痕-对应的的进店数据
        $bh_entershop = Db::name('customer')->alias('a')
            ->join('customer_scar b', 'a.id = b.customer_id', 'left')
            ->field('count(distinct a.id) as num')
            ->where($where)
            ->where(function ($query) use ($whereOr) {
                $query->whereOr($whereOr);
            })->select()->toArray();
        //痘痘
        $where = array_merge($baseWhere, [['b.customer_setting_id_type', 'in', $dd]]);
        $dd_entershop = Db::name('customer')->alias('a')
            ->join('customer_scar b', 'a.id = b.customer_id', 'left')
            ->field('count(a.id) as num')
            ->where($where)
            ->where(function ($query) use ($whereOr) {
                $query->whereOr($whereOr);
            })->select()->toArray();
        //项目
        $where = array_merge($baseWhere, [['b.customer_setting_id_type', 'in', $xm]]);
        $xm_entershop = Db::name('customer')->alias('a')
            ->join('customer_scar b', 'a.id = b.customer_id', 'left')
            ->field('count(a.id) as num')
            ->where($where)
            ->where(function ($query) use ($whereOr) {
                $query->whereOr($whereOr);
            })->select()->toArray();
        return [
            'bh_entershop'=>$bh_entershop,
            'dd_entershop'=>$dd_entershop,
            'xm_entershop'=>$xm_entershop
        ];
    }
    //A客分析
    public function ACustomerAnalyse($shopIds,$request){

        list($shop_type,$market_id,$shop_id,$time_type,$start_time,$end_time) = $this->getPublicSearch($request);
        $shop_where = [];
        array_push($shop_where,['shop_type','=',$shop_type]);
        array_push($shop_where,['type','<>','2']);
        array_push($shop_where,['status','=','1']);
        if(!empty($market_id)){
            array_push($shop_where,['market_id','=',$market_id]);
        }
        if(!empty($shop_id)){
            array_push($shop_where,['shop_id','=',$shop_id]);
        }
        if(!empty($shopIds)){
            array_push($shop_where,['shop_id','in',$shopIds]);
        }
        $shopIds = ShopModel::where($shop_where)->column('shop_id'); //门店
        $mz_shopIds = ShopModel::where(['shop_type'=>1,'status'=>1])->column('shop_id'); //门诊

        $startTime = date('Y')."0101";
        $endTime = date('Ymd');
        $map = [
            ['shop_id','in',$shopIds],
            ['customer_level','=',73],
            ['date','between',"$startTime,$endTime"]
        ];
        $c_map = [
            ['shop_id','in',$shopIds],
            ['member_classification','=',73],
        ];

        $customer_id = Db::name('customer')->where('cj_time','>',0)->where('cj_money','>=',500)->where($c_map)->column('id');


        $where = [];
        array_push($where,['date','between',"$startTime,$endTime"]);

        $c_id  = Db::name('customer_consumption_log')->where($map)->column('customer_id');


        $now_customer_id = array_intersect($c_id,$customer_id);

        $c_phone  = Db::name('customer_consumption_log')->where($map)->whereIn('customer_id',$now_customer_id)->column('customer_phone');





        $Acustomer = Db::name('customer_consumption_log')
            ->where($where)
            ->whereIn('customer_phone',$c_phone)
            ->field('customer_phone,sum(consumption_sum) as consumption_sum')
            ->group('customer_phone')
            ->select()->toArray(); //门店的客户数据


//        $Acustomer = Db::name('customer_consumption_log')->where($map)->field('customer_id,sum(consumption_sum) as consumption_sum')->group('customer_id')->select()->toArray(); //门店的客户数据

        $a = $b = $c = [];
        foreach($Acustomer as $key=>$v){

//            $shop_expenditure = $this->getCustomerExpenditure([$v['id']],$startTime,$endTime);
//            $mz_customer_id = Customer::where('telephone',$v['telephone'])->whereIn('shop_id',$mz_shopIds)->column('id'); //门诊的的客户数据
//            $mz_expenditure = 0;
//            if(!empty($mz_customer_id)){
//                $mz_expenditure = $this->getCustomerExpenditure($mz_customer_id,$startTime,$endTime);
//            }
//            $expenditure = bcadd($shop_expenditure,$mz_expenditure,2);
            $expenditure = $v['consumption_sum'];
            if($expenditure>50000){
                array_push($a,$v['customer_phone']);
            }else if($expenditure <=50000 && $expenditure >=30000){
                array_push($b,$v['customer_phone']);
            }else if($expenditure <30000){
                array_push($c,$v['customer_phone']);
            }
        }
        $a = count($a);
        $b = count($b);
        $c = count($c);
        return ['consumption'=>[$a,$b,$c]];
    }
    //B客分析
    public function BCustomerAnalyse($shopIds,$request){
        list($shop_type,$market_id,$shop_id,$time_type,$start_time,$end_time) = $this->getPublicSearch($request);
        $shop_where = [];
        array_push($shop_where,['shop_type','=',$shop_type]);
        array_push($shop_where,['type','<>','2']);
        array_push($shop_where,['status','=','1']);
        if(!empty($market_id)){
            array_push($shop_where,['market_id','=',$market_id]);
        }
        if(!empty($shop_id)){
            array_push($shop_where,['shop_id','=',$shop_id]);
        }

        if(!empty($shopIds)){
            array_push($shop_where,['shop_id','in',$shopIds]);
        }
        $shopIds = ShopModel::where($shop_where)->column('shop_id'); //门店
        $mz_shopIds = ShopModel::where(['shop_type'=>1,'status'=>1])->column('shop_id'); //门诊
        $startTime = date('Y')."0101";
        $endTime = date('Ymd');
        $map = [
            ['shop_id','in',$shopIds],
            ['customer_level','=',72],
            ['date','between',"$startTime,$endTime"]
        ];
        $c_map = [
            ['shop_id','in',$shopIds],
            ['member_classification','=',72],
        ];

        $customer_id = Db::name('customer')->where('cj_time','>',0)->where('cj_money','>=',500)->where($c_map)->column('id');

        $where = [];
        array_push($where,['date','between',"$startTime,$endTime"]);

        $c_id  = Db::name('customer_consumption_log')->where($map)->column('customer_id');

        $now_customer_id = array_intersect($c_id,$customer_id);

        $c_phone  = Db::name('customer_consumption_log')->where($map)->whereIn('customer_id',$now_customer_id)->column('customer_phone');

        $Bcustomer = Db::name('customer_consumption_log')
            ->where($where)
            ->whereIn('customer_phone',$c_phone)
            ->field('customer_phone,sum(consumption_sum) as consumption_sum')
            ->group('customer_phone')
            ->select()->toArray(); //门店的客户数据
//        $Bcustomer = Db::name('customer_consumption_log')->where($map)->field('customer_id,sum(consumption_sum) as consumption_sum')->group('customer_id')->select()->toArray(); //门店的客户数据 //门店的客户数据


        $a = $b = $c = [];
        foreach($Bcustomer as $key=>$v){
//            $shop_expenditure = $this->getCustomerExpenditure([$v['id']],$startTime,$endTime);
//            $mz_customer_id = Customer::where('telephone',$v['telephone'])->whereIn('shop_id',$mz_shopIds)->column('id'); //门诊的的客户数据
//            $mz_expenditure = 0;
//            if(!empty($mz_customer_id)){
//                $mz_expenditure = $this->getCustomerExpenditure($mz_customer_id,$startTime,$endTime);
//            }
//            $expenditure = bcadd($shop_expenditure,$mz_expenditure,2);
            $expenditure = $v['consumption_sum'];
            if($expenditure <=50000 && $expenditure >=30000){
                array_push($a,$v['customer_phone']);
            }else if($expenditure <=30000 && $expenditure >=15000){
                array_push($b,$v['customer_phone']);
            }else if($expenditure <15000){
                array_push($c,$v['customer_phone']);
            }
        }
        $a =count($a);
        $b = count($b);
        $c = count($c);
        return ['consumption'=>[$a,$b,$c]];
    }
    //A/B客户分析-价值分析
    public function getCustomerExpenditure($customer_id,$startTime,$endTime){
        //收款单
        $receive = Db::name('shop_refund_order')
            ->field('sum(pay_amount) as pay_amount')
            ->whereIn('uid',$customer_id)
            ->where('type','=',3)
            ->where('status','=',2)
            ->where('refund_type','=','101.02')
            ->whereBetween('deal_time',[$startTime,$endTime])
            ->find();
        //退款单
        $refund = Db::name('shop_refund_order')->alias('r')
            ->join('shop_refund_order_goods g', 'r.id=g.order_id', 'LEFT')
            ->field('sum(r.pay_amount) as pay_amount')
            ->where('g.refund_mode','<>','06')
            ->whereIn('uid',$customer_id)
            ->where('r.type','=',1)
            ->where('r.status','=',2)
            ->where('r.refund_type','=','101.02')
            ->whereBetween('deal_time',[$startTime,$endTime])
            ->find();

        return bcsub($receive['pay_amount'],$refund['pay_amount'],2);
    }
    //品项分析
    public function ItemAnalysis($shopIds,$request){
        list($shop_type,$market_id,$shop_id,$time_type,$start_time,$end_time) = $this->getPublicSearch($request);
        $where =[];
        array_push($where,['shop_type','=',$shop_type]);
        if(!empty($shopIds)){
            array_push($where,['shop_id','id',$shopIds]);
        }
        if(!empty($market_id)){
            array_push($where,['market_id','=',$market_id]);
        }
        if(!empty($shopIds)){
            array_push($shop_id,['shop_id','=',$shop_id]);
        }
        $return =[];
        $shopList = ShopModel::field('shop_id as shopId,market_id as marketId, shop_type')
            ->where($where)->select()->toArray();
        if(!empty($shopList)){
            $scarMoneyAll =ShopModel::sumShopPayMoneyNewMZAll('Bh',$start_time,$end_time);

            $projectStMoneyAll = ShopModel::sumShopPayMoneyNewMZAll('STXM',$start_time,$end_time); //身体项目

            $projectPfMoneyAll = ShopModel::sumShopPayMoneyNewMZAll('PFXM',$start_time,$end_time); //皮肤项目

            $qcdMoneyAll = ShopModel::sumShopPayMoneyNewMZAll('QCD',$start_time,$end_time); // 青春痘

            $hfpMoneyAll =ShopModel::sumShopPayMoneyNewMZAll('HFP',$start_time,$end_time); // 护肤品

            //疤痕
            $scarMoneyAllOne =ShopModel::sumShopPayMoneyNewAll('Bh',1,$start_time,$end_time);

            $scarMoneyAllTwo =ShopModel::sumShopPayMoneyNewAll('Bh',2,$start_time,$end_time);
            //身体项目
            $projectStMoneyAllOne = ShopModel::sumShopPayMoneyNewAll('STXM',1,$start_time,$end_time);

            $projectStMoneyAllTwo = ShopModel::sumShopPayMoneyNewAll('STXM',2,$start_time,$end_time);
            //皮肤项目
            $projectPfMoneyAllOne = ShopModel::sumShopPayMoneyNewAll('PFXM',1,$start_time,$end_time);

            $projectPfMoneyAllTwo = ShopModel::sumShopPayMoneyNewAll('PFXM',2,$start_time,$end_time);
            // 青春痘
            $qcdMoneyAllOne =ShopModel::sumShopPayMoneyNewAll('QCD',1,$start_time,$end_time);

            $qcdMoneyAllTwo =ShopModel::sumShopPayMoneyNewAll('QCD',2,$start_time,$end_time);
            // 护肤品
            $hfpMoneyAllOne = ShopModel::sumShopPayMoneyNewAll('HFP',1,$start_time,$end_time);

            $hfpMoneyAllTwo = ShopModel::sumShopPayMoneyNewAll('HFP',2,$start_time,$end_time);


            $bh_num = $stxm_num = $pfxm_num = $qcd_num = $hfp_num = 0;

            $bh_money = $stxm_money = $pfxm_money = $qcd_money = $hfp_money = 0;
            foreach($shopList as $k=>$v){
                //转诊金额计算  川渝市场和门诊的转诊  都是 默认 0 不计算 对接财务确定；2022-07-24
                if(in_array($v['marketId'],[8,9,10,11]) ){
                    //疤痕业绩计算--川渝市场
                    $scarMoney = empty($scarMoneyAll[$v['shopId']])?0:$scarMoneyAll[$v['shopId']];// 疤痕
                    $projectStMoney = empty($projectStMoneyAll[$v['shopId']])?0:$projectStMoneyAll[$v['shopId']];// 身体项目
                    $projectPfMoney = empty($projectPfMoneyAll[$v['shopId']])?0:$projectPfMoneyAll[$v['shopId']];// 皮肤项目
                    $qcdMoney = empty($qcdMoneyAll[$v['shopId']])?0:$qcdMoneyAll[$v['shopId']];// 青春痘
                    $hfpMoney = empty($hfpMoneyAll[$v['shopId']])?0:$hfpMoneyAll[$v['shopId']];// 护肤品
                }else{
                    if($v['shop_type'] == 1)
                    {
                        $scarMoney = empty($scarMoneyAllOne[$v['shopId']])?0:$scarMoneyAllOne[$v['shopId']];
                        $projectStMoney = empty($projectStMoneyAllOne[$v['shopId']])?0:$projectStMoneyAllOne[$v['shopId']];// 身体项目
                        $projectPfMoney = empty($projectPfMoneyAllOne[$v['shopId']])?0:$projectPfMoneyAllOne[$v['shopId']];// 皮肤项目
                        $qcdMoney = empty($qcdMoneyAllOne[$v['shopId']])?0:$qcdMoneyAllOne[$v['shopId']];// 青春痘
                        $hfpMoney = empty($hfpMoneyAllOne[$v['shopId']])?0:$hfpMoneyAllOne[$v['shopId']];// 护肤品
                    }else{
                        $scarMoney = empty($scarMoneyAllTwo[$v['shopId']])?0:$scarMoneyAllTwo[$v['shopId']];
                        $projectStMoney = empty($projectStMoneyAllTwo[$v['shopId']])?0:$projectStMoneyAllTwo[$v['shopId']];// 身体项目
                        $projectPfMoney = empty($projectPfMoneyAllTwo[$v['shopId']])?0:$projectPfMoneyAllTwo[$v['shopId']];// 皮肤项目
                        $qcdMoney = empty($qcdMoneyAllTwo[$v['shopId']])?0:$qcdMoneyAllTwo[$v['shopId']];// 青春痘
                        $hfpMoney = empty($hfpMoneyAllTwo[$v['shopId']])?0:$hfpMoneyAllTwo[$v['shopId']];// 护肤品
                    }
                }
                $Bh = $this->getConsumptionData('Bh',$v['shopId'],$start_time,$end_time);
                $STXM = $this->getConsumptionData('STXM',$v['shopId'],$start_time,$end_time);
                $PFXM = $this->getConsumptionData('PFXM',$v['shopId'],$start_time,$end_time);
                $QCD = $this->getConsumptionData('QCD',$v['shopId'],$start_time,$end_time);
                $HFP = $this->getConsumptionData('HFP',$v['shopId'],$start_time,$end_time);

                $bh_num = $bh_num+$Bh;
                $stxm_num = $stxm_num+$STXM;
                $pfxm_num = $pfxm_num+$PFXM;
                $qcd_num = $qcd_num+$QCD;
                $hfp_num = $hfp_num+$HFP;

                $bh_money = bacdd($bh_money,$scarMoney,2);
                $stxm_money = bacdd($stxm_money,$projectStMoney,2);
                $pfxm_money = bacdd($pfxm_money,$projectPfMoney,2);
                $qcd_money = bacdd($qcd_money,$qcdMoney,2);
                $hfp_money = bacdd($hfp_money,$hfpMoney,2);

            }
            $return['bh'] = ['num'=>$bh_num,'price'=>$bh_money];
            $return['stxm'] = ['num'=>$stxm_num,'price'=>$stxm_money];
            $return['pfxm'] = ['num'=>$pfxm_num,'price'=>$pfxm_money];
            $return['qcd'] = ['num'=>$qcd_num,'price'=>$qcd_money];
            $return['hfp'] = ['num'=>$hfp_num,'price'=>$hfp_money];
            $return['ym'] = ['num'=>0,'price'=>0.00];
            return $return;
        }
    }
    //获取业绩人数
    public function getConsumptionData($type,$shopId,$startTime,$endTime){
        $where = [];
        switch ($type){
            case 'Bh':
                $where['r.business_type'] = 1;
                break;
            case 'STXM':
                $where['r.business_type'] = 2;
                $where['r.business_two_type'] = 1;
                break;
            case 'PFXM':
                $where['r.business_type'] = 2;
                $where['r.business_two_type'] = 2;
                break;
            case 'QCD':
                $where['r.business_type'] = 3;
                break;
            case 'HFP':
                $where['r.business_type'] = 4;
                break;
            default:
                break;
        }

        //收款单 收款类型是 收款 且不含收款方式不是店转的
        $receive = Db::name('shop_refund_order')->alias('r')

            ->field('sum(g.pay_price) as pay_amount,r.uid')

            ->where($where)

            ->where('r.shop_id','=',$shopId)

            ->where('g.refund_mode','<>','06')

            ->where('r.type','=',3)

            ->where('r.status','=',2)

            ->where('r.refund_type','=','101.02')

            ->when($startTime ?? 0, function ($query) use ($startTime) {
                return $query->whereTime('deal_time', '>=', $startTime);
            })
            ->when($endTime ?? 0, function ($query) use ($endTime) {
                return $query->whereTime('deal_time', '<=', $endTime);
            },function ($query) use ($endTime) {
                return $query->whereMonth('deal_time');
            })
            ->group('r.uid')
            ->having('pay_amount>0')
            ->select()->toArray();
        //退款单
        $refund = Db::name('shop_refund_order')->alias('r')

            ->field('sum(r.pay_amount) as pay_amount,r.uid')

            ->where($where)

            ->where('r.shop_id','=',$shopId)

            ->where('g.refund_mode','<>','06')

            ->where('r.type','=',1)

            ->where('r.status','=',2)

            ->where('r.refund_type','=','101.02')

            ->when($startTime ?? 0, function ($query) use ($startTime) {
                return $query->whereTime('deal_time', '>=', $startTime);
            })
            ->when($endTime ?? 0, function ($query) use ($endTime) {
                return $query->whereTime('deal_time', '<=', $endTime);
            },function ($query) use ($endTime) {
                return $query->whereMonth('deal_time');
            })
            ->group('r.uid')
            ->having('pay_amount>0')
            ->select()->toArray();

        $receipt_uids = array_column($receive,'uid');
        $refund_uids = array_column($refund,'uid');
        $jiaoji_uids = array_intersect($receipt_uids,$refund_uids);//获取收款单和退款单相同的客户id
        $receipt_diff_count = count(array_diff($refund_uids,$jiaoji_uids)); //获取仅有收款单的客户id数
        foreach($jiaoji_uids as $k=>$v){
            if($receive[$v]['pay_amount'] <= $refund[$v]['pay_amount']){
                unset($jiaoji_uids[$k]);
            }
        }
        $jiaoji_uids_count = count($jiaoji_uids);
        $count = $receipt_diff_count+$jiaoji_uids_count;
        return $count;
    }
    //品相排序
    public function getItemData($shopIds,$request){
        list($shop_type,$market_id,$shop_id,$time_type,$start_time,$end_time) = $this->getPublicSearch($request);
        $ymxm = $ymxmData  = $pfxm = $pfxmData  = $hfp = $hfpData = [];
        $where = [];
        array_push($where,['shop_id','in',$shopIds]);
        array_push($where,['shop_type','=',$shop_type]);
        if(!empty($market_id)){
            array_push($where,['market_id','=',$market_id]);
        }
        if(!empty($shop_id)){
            array_push($where,['shop_id','=',$shop_id]);
        }
        $shopIds = ShopModel::where($where)->column('shop_id');
        $ymxmData = $this->getItemDataOrder($ymxm,$shopIds,$start_time,$end_time);
        foreach($ymxmData['dataFront'] as $k=>&$v){
            $v['serve_name'] =  !empty($v['goods']) ?$v['goods']['name']:'服务数据异常';
            $v['man_time'] = 100;
            $v['img'] = '';
        }
        foreach($ymxmData['dataBehind'] as $k=>&$v){
            $v['serve_name'] =  !empty($v['goods']) ?$v['goods']['name']:'服务数据异常';
            $v['man_time'] = 100;
            $v['img'] = '';
        }

        $pfxmData = $this->getItemDataOrder($pfxm,$shopIds,$start_time,$end_time);

        foreach($pfxmData['dataFront'] as $k=>&$v){
            $v['serve_name'] =  !empty($v['goods']) ?$v['goods']['name']:'服务数据异常';
            $v['man_time'] = 100;
            $v['img'] = '';
        }
        foreach($pfxmData['dataBehind'] as $k=>&$v){
            $v['serve_name'] =  !empty($v['goods']) ?$v['goods']['name']:'服务数据异常';
            $v['man_time'] = 100;
            $v['img'] = '';
        }
        $hfpData = $this->getItemDataOrder($hfp,$shopIds,$start_time,$end_time);

        foreach($hfpData['dataFront'] as $k=>&$v){
            $v['serve_name'] =  !empty($v['goods']) ?$v['goods']['name']:'服务数据异常';
            $v['man_time'] = 100;
            $v['img'] = '';
        }

        foreach($hfpData['dataBehind'] as $k=>&$v){
            $v['serve_name'] =  !empty($v['goods']) ?$v['goods']['name']:'服务数据异常';
            $v['man_time'] = 100;
            $v['img'] = '';
        }
        return ['ymxmData'=>$ymxmData,'pfxmData'=>$pfxmData,'hfpData'=>$hfpData];

    }
    //获取各个品相的排序
    public function getItemDataOrder($goods_id,$shopIds,$start_time,$end_time){
        $where = [];
        if(!empty($goods_id)){
            array_push($where,['goods_id','in',$goods_id]);
        }
        if(!empty($shopIds)){
            array_push($where,['shop_id','in',$shopIds]);
        }
        if(!empty($start_time) && !empty($end_time)){
            array_push($where,['create_time','between',"$start_time,$end_time"]);
        }
        $shopOrderGoodsDesc = ShopOrderGoodsModel::with(['goods'=>function($query){
            $query->field('name,id');
        }])->field('count(id) as count,goods_id')->where($where)->group('goods_id')->order('count','desc')->limit(10)->select()->toArray();
        $shopOrderGoodsAsc = ShopOrderGoodsModel::with(['goods'=>function($query){
            $query->field('name,id');
        }])->field('count(id) as count,goods_id')->where($where)->group('goods_id')->order('count','asc')->limit(5)->select()->toArray();
        return ['dataFront'=>$shopOrderGoodsDesc,'dataBehind'=>$shopOrderGoodsAsc];
    }
    //员工分析-上头的
    public function getShopSumData($shopIds,$request){
        list($shop_type,$market_id,$shop_id,$time_type,$start_time,$end_time) = $this->getPublicSearch($request);
        if(!empty($shop_ids)){
            $shop_id = $shop_ids[0];
        }else{
            $map=[
                ['shop_type','=',$shop_type],
                ['status','=',1],
                ['type','<>',2]
            ];
            $shop_id = DB::name('shop')->where($map)->value('shop_id');
        }
        $supplerPerson =  $this->supplePerson($shop_id,$start_time,$end_time); //补单业绩
        list($customer_count,$days,$avgCustomer) = $this->dailyCustomer($shop_id,$start_time,$end_time); //客户档案以及日均客户数
        list($baoyou_customer_count,$lost_customer_count) = $this->byandLostCustomer($shop_id,$start_time,$end_time); //保有顾客以及流失顾客
        list($amountCare,$days,$aveCare) = $this->byandLostCustomer($shop_id,$start_time,$end_time); //日均护理量
        $return = [
          'supplerPerson'=>$supplerPerson,
            'customer_count'=>$customer_count,
            'dayAveCustomer' =>$avgCustomer,
            'by_customer_count' =>$baoyou_customer_count,
            'lost_customer_count' =>$lost_customer_count,
            'dayAveCare' => $aveCare
        ];
        return $return;
    }
    //员工-分析
    public function getPersonData($shop_ids,$request){
        list($shop_type,$market_id,$shop_id,$time_type,$start_time,$end_time) = $this->getPublicSearch($request);

        if(!empty($shop_ids)){
            $shop_id = $shop_ids[0];
        }else{
            $map=[
                ['shop_type','=',$shop_type],
                ['status','=',1],
                ['type','<>',2]
            ];
            if(empty($shop_id)){
                $shop_id = DB::name('shop')->where($map)->value('shop_id');
            }
        }

        $shopData = DB::name('shop')->where('shop_id',$shop_id)->field('shop_type,market_id,shop_id')->find();
        $market_id = $shopData['market_id']; //门店的所属市场id
        $where =[
            ['shop_id','=',$shop_id],
            ['status','=',1],
            ['name','<>','虚拟员工核销专用']
        ];
        $personData = DB::name('shop_person')->where($where)->field('name,id')->select()->toArray();

        $customer_data = $this->getPersonCustomerData($shop_id);
        $customer_data = array_column($customer_data,null,'nurse_id');

        $model = new ReserveandLost();
        $orderStatisticsModel = new OrderStatistics();
        $shopModel = new ShopModel();

        $today = date('Y-m-d',time());

        $shop_ids = [$shop_id];

        $performance =[];
        $personName = [];
        $bdyj = [];
        $hll = [];
        $hls = [];
        $hlzs = [];

        foreach($personData as $key=>&$v){
            $wl_num = DB::name('customer')->where('nurse_id',$v['id'])->whereBetween('create_time',"$start_time,$end_time")->where('source_id',46)->count();
            $v['wl_customer_num'] = $wl_num;
            $zjs_num = DB::name('customer')->where('introducer',$v['id'])->whereBetween('create_time',"$start_time,$end_time")->count();
            $v['zjs_customer_num']= $zjs_num;
            $where =[
                ['selection_results','in',[2,3]],
                ['nurse_id','=',$v['id']],
                ['tg_excellent_time','between',"$start_time,$end_time"]
            ];
            $ya_num = Db::name('case')->where($where)->count();

            $v['ya_num']= $ya_num;

            $v['person_name'] = $v['name'];
            $v['customer_count'] = isset($customer_data[$v['id']])?$customer_data[$v['id']]['count']:0; //客户数
            $baoyou_customer = $lost_customer = [];
            $map = [
                ['shop_id','=',$shop_id],
                ['cj_time','<',$end_time],
                ['cj_time','<>',0],
                ['cj_money','<>',0],
                ['nurse_id','=',$v['id']]
            ];
            $cj_customer =  Customer::where($map)->column('id');
            if(!empty($cj_customer)){
                $lost_caseIds = $model->lost_case($cj_customer,$today);
                // 成交客户
                $cj_customer = array_diff($cj_customer,$lost_caseIds); //最终成交的顾客id
                if(!empty($cj_customer)){
                    // 保有顾客数
                    $baoyou_customer = $model->baoyou_customer($cj_customer,$today);
                    // 流失顾客数
                    $lost_customer = $model->lost_customer($cj_customer,$today);
                }
            }
            $v['customer_by'] = count($baoyou_customer); //保有顾客数
            $v['customer_ls'] = count($lost_customer);//保有流失数


            //日均护理量，以及日均护理人数
            list($day,$aveCare,$aveCareNum,$amountCare) = $this->personAveCareCountandNum($shop_id,$start_time,$end_time,$v['id']);
            $v['amountCare'] = $amountCare; //护理总数
            array_push($hlzs,$v['amountCare']);
            $v['care_amount_dayavg'] = $aveCare;
            array_push($hll,$v['care_amount_dayavg']);
            $v['care_customer_dayavg'] = $aveCareNum;
            array_push($hls,$v['care_customer_dayavg']);

            $nine_start_time = 1725120000; //24年9月1日 0：00：00
            $sepbdMoney = $sepxdMoney = $budanMoney =  $newsXDMoney = 0;
            if( $start_time >= $nine_start_time && $end_time > $nine_start_time ){

                //走一批
                $bdyeji = $shopModel->shopPerform($shop_ids,2,$start_time,$end_time,0,0,$v['id']);
                $xdyeji = $shopModel->shopPerform($shop_ids,1,$start_time,$end_time,0,0,$v['id']);
                $sepbdMoney = isset($bdyeji[$shop_id])?$bdyeji[$shop_id]:0; //补单
                $sepxdMoney = isset($xdyeji[$shop_id])?$xdyeji[$shop_id]:0; //新单
            }else{
                //走两批
                $bdyeji = $shopModel->shopPerform($shop_ids,2,$nine_start_time,$end_time,0,0,$v['id']);
                $xdyeji = $shopModel->shopPerform($shop_ids,1,$nine_start_time,$end_time,0,0,$v['id']);
                $sepbdMoney = isset($bdyeji[$shop_id])?$bdyeji[$shop_id]:0; //补单
                $sepxdMoney = isset($xdyeji[$shop_id])?$xdyeji[$shop_id]:0; //新单
                $end_time = 1725119999; //24年8月31日 23 59 59
                if(in_array($shopData['market_id'],[8,9,10,11])){
                    $newsXDMoney = $orderStatisticsModel->sumShopPayMoneyNewMZ('XD',$shopData['shop_id'],$shopData['shop_type'],$start_time,$end_time,$v['id']);
                    $budanMoney = $orderStatisticsModel->sumShopPayMoneyNewMZ('BD',$shopData['shop_id'],$shopData['shop_type'],$start_time,$end_time,$v['id']);
                }else{
                    $newsXDMoney = $orderStatisticsModel->sumShopPayMoneyNew('XD',$shopData['shop_id'],$shopData['shop_type'],$start_time,$end_time,$v['id']);
                    $budanMoney = $orderStatisticsModel->sumShopPayMoneyNew('BD',$shopData['shop_id'],$shopData['shop_type'],$start_time,$end_time,$v['id']);
                }
            }

            //补单业绩
            $v['replenishment'] = bcadd($budanMoney,$sepbdMoney,2);
            array_push($bdyj,$v['replenishment']);
            //总业绩
            $old = bcadd($newsXDMoney,$budanMoney,2);
            $new = bcadd($sepbdMoney,$sepxdMoney,2);
            $v['performance'] = bcadd($old,$new);
            array_push($performance,$v['performance']);

            array_push($personName,$v['name']);
        }
        return ['list'=>$personData,'replenishment'=>$bdyj,'hll'=>$hll,'hls'=>$hls,'hlzs'=>$hlzs,'personName'=>$personName,'shop_id'=>$shop_id,'market_id'=>$market_id,'performance'=>$performance];
    }
    //单个护理师 人均护理量-人均护理人数
    public function personAveCareCountandNum($shop_id,$start_time,$end_time,$person_id){
        $map = [
            ['shop_id','=',$shop_id],
            ['create_time','between',"$start_time,$end_time"],
            ['is_cancel','<>',2],
            ['nurse_id_one|nurse_id_two','=',$person_id]
        ];
        $amountCare = DB::name('service_log')->where($map)->count();

        $amountCareNum  = DB::name('service_log')->where($map)->column('customer_id');

        $amountCareNum = count(array_unique($amountCareNum));

        $days = $this->getDay($start_time,$end_time);
        $aveCare = $aveCareNum =  0;
        if($days > 0){
            $aveCare = bcdiv($amountCare,$days);
            $aveCareNum = bcdiv($amountCareNum,$days);
        }
        return [$days,$aveCare,$aveCareNum,$amountCare];
    }

    //获取流失原因-暂时去除
    public function getDrainCauses($customer_id,$reason_id){
        return Customer::whereIn('id',$customer_id)->whereRaw('member_label',$reason_id)->column('id');
    }
    //员工分析-客户数
    public function getPersonCustomerData($shop_id){
        return Customer::where('shop_id',$shop_id)->field('count(id) as count,nurse_id')->group('nurse_id')->select()->toArray();
    }


    //员工分析-保有顾客-流失顾客
    public function byandLostCustomer($shop_id,$start_time,$end_time){

        $model = new ReserveandLost();
        $shopIds = [];
        array_push($shopIds,$shop_id);
        $cj_type = 0;
        $today = date('Y-m-d',time());
        // 总成交顾客数
        $cj_customer = $model->cj_customer($shopIds,['cj_type' => $cj_type]);
        // 保有顾客数
        $baoyou_customer = $model->baoyou_customer($cj_customer,$today);
        $baoyou_customer_count = count($baoyou_customer);

        // 流失顾客数
        $lost_customer = $model->lost_customer($cj_customer,$today);
        $lost_customer_count = count($lost_customer);

        return [$baoyou_customer_count,$lost_customer_count];
    }

    //员工分析-日均护理量
    public function aveCare($shop_id,$start_time,$end_time){
        $map = [
            ['shop_id','=',$shop_id],
            ['create_time','between',"$start_time,$end_time"],
            ['is_cancel','<>',2]
        ];
        $amountCare = DB::name('service_log')->where($map)->count();
        $days = $this->getDay($start_time,$end_time);
        $aveCare = 0;
        if($days>0){
            $aveCare = bcdiv($amountCare,$days);
        }
        return [$amountCare,$days,$aveCare];
    }

    //员工分析-日均客户数
    public function dailyCustomer($shop_id,$start_time,$end_time){
        $count = Customer::where('shop_id',$shop_id)->whereBetween('create_time',"$start_time,$end_time")->count();
        $days = $this->getDay($start_time,$end_time);

        $avgCustomer =  !empty($days)?bcdiv($count,$days):0 ;

        return [$count,$days,$avgCustomer];
    }
    //通过两个时间戳获取天数
    public function getDay($start_time,$end_time){
        $diff = abs($end_time-$start_time);
        $days = floor($diff / (60 * 60 * 24));
        return $days<1?1:$days;
    }

    //员工分析-补单业绩
    public function supplePerson($shop_data,$start_time,$end_time){
        $orderStatisticsModel = new OrderStatistics();
        $nine_start_time = 1725120000; //24年9月1日 0：00：00
        $sepbudanMoney =  $budanMoney = 0;
        if( $start_time >= $nine_start_time && $end_time > $nine_start_time){
            // 走一批
            $shopModel = new ShopModel();
            $bdyeji = $shopModel->shopPerform([$shop_data['shop_id']],2,$start_time,$end_time);
            $sepbudanMoney = isset($bdyeji[$shop_data['shop_id']]) ? $bdyeji[$shop_data['shop_id']]:0;

        }else{
            //走两批
            $shopModel = new ShopModel();
            $bdyeji = $shopModel->shopPerform([$shop_data['shop_id']],2,$nine_start_time,$end_time);
            $sepbudanMoney = isset($bdyeji[$shop_data['shop_id']]) ? $bdyeji[$shop_data['shop_id']]:0;
            $end_time = 1725119999; //24年8月31日 23 59 59
            if (in_array($shop_data['market_id'], [8, 9, 10, 11])) {
                $budanMoney = $orderStatisticsModel->sumShopPayMoneyNewMZ('BD', $shop_data['shop_id'], $shop_data['shop_type'], $start_time, $end_time);
            } else {
                $budanMoney = $orderStatisticsModel->sumShopPayMoneyNew('BD', $shop_data['shop_id'], $shop_data['shop_type'], $start_time, $end_time);
            }
        }
        return bcadd($sepbudanMoney,$budanMoney,2);
    }


    //公共搜索用到的数据
    public function getShopData($shopIds,$request){

        list($shop_type,$market_id,$shop_id,$time_type,$start_time,$end_time) = $this->getPublicSearch($request);
        $where =[
            ['shop_type','=',$shop_type],
            ['status','=',1],
            ['type','<>',2]
        ];
        if(!empty($shopIds)){
            array_push($where,['shop_id','in',$shopIds]);
        }
        if(!empty($shop_id)) {
            array_push($where,['shop_id','=',$shop_id]);
        }
        $shop_data = DB::name('shop')->field('shop_id as value,shop_name as lable,market_id')->where($where)->select()->toArray();
        if(!empty($shop_data)){
            $market_ids = array_unique(array_column($shop_data,'market_id'));
            $market_data = DB::name('shop_market')->field('id as value,name as lable')->whereIn('id',$market_ids)->select()->toArray();
        }else{
            $market_data = DB::name('shop_market')->field('id as value,name as lable')->select()->toArray();
        }
        return ['shop'=>$shop_data,'market'=>$market_data];
    }


    //累计客户保有数
    public function ShopRetainCustomers($shopIds,$request){
        //公共查询条件
        list($shop_type,$market_id,$shop_id,$time_type,$start_time,$end_time) = $this->getPublicSearch($request);
        $where = $lj_by_one = $baoyou_sum = $last_lj_by_one =  [];
        array_push($where,['shop_type','=',$shop_type]);
        if($market_id >0){
            array_push($where,['market_id','=',$market_id]);
        }
        if($shop_id> 0){
            array_push($where,['shop_id','=',$shop_id]);
        }
        if(!empty($shopIds)){
            array_push($where,['shop_id','in',$shopIds]);
        }

        $month = date('m',time()); //当前时间的月份
        $day = date('d',time()); //当前时间的天数
        $year = date('Y',time()); //当前时间的年

        $last_year = (string)$year-1;

        $begin_month = date('m',$start_time);
        $end_month  = date('m',$end_time);

        for ($i=1;$i<=12;$i++){
            $baoyou_sum = 0;
            if($i > $month){
                $baoyou_sum = 0;
                $last_baoyou_sum = 0;
            }else{
                $end_day = date('Ymt',strtotime(date('Y-'.$i.'-01')));
                $last_end_day = date ( "Ymd" , strtotime ("-1 years",strtotime($end_day)));

                if($i==$month){
                    $end_day = date('Ymd',strtotime ( "-1 day" ));
                    $last_end_day = date ( "Ymd" , strtotime ("-1 years",strtotime($end_day)));
                }

                $map = [];
                array_push($map,['date','=',$end_day]);
                $baoyou = DB::name('shop_total_log')->where($where)->where($map)->column('by_total_num');

                $last_map = [];
                array_push($last_map,['date','=',$last_end_day]);
                $last_baoyou = DB::name('shop_total_log')->where($where)->where($last_map)->column('by_total_num');

                $baoyou_sum = array_sum($baoyou);

                $last_baoyou_sum = array_sum($last_baoyou);
            }
            array_push($lj_by_one,$baoyou_sum);
            array_push($last_lj_by_one,$last_baoyou_sum);
        }

        return ['lj_by_one'=>$lj_by_one,'last_lj_by_one'=>$last_lj_by_one,'year'=>[$year,$last_year]];
    }
    //周期性保有保有顾客数
    public function periodicityBaoyou($shopIds,$request){
        list($shop_type,$market_id,$shop_id,$time_type,$start_time,$end_time) = $this->getPublicSearch($request);
        $where = $map = $zqx_by_one = $last_zqx_by_one =  [];

        array_push($where,['shop_type','=',$shop_type]);
        if($market_id >0){
            array_push($where,['market_id','=',$market_id]);
        }
        if($shop_id> 0){
            array_push($where,['shop_id','=',$shop_id]);
        }
        if(!empty($shopIds)){
            array_push($where,['shop_id','in',$shopIds]);
        }

        $month = date('m',time()); //当前时间的月份
        $day = date('d',time()); //当前时间的月份
        $year = date('Y',time()); //当前时间的年份
        $last_year = $year-1; //去年

        for ($i=1;$i<=12;$i++){
            if($i > $month){
                $baoyou_sum = 0;
                $last_baoyou_sum = 0;
            }else{

                $end_day = date('Ymt',strtotime(date('Y-'.$i.'-01')));
                $last_end_day = date ( "Ymd" , strtotime ("-1 years",strtotime($end_day)));

                if($i==$month){
                    $end_day = date('Ymd',strtotime ( "-1 day" ));
                    $last_end_day = date ( "Ymd" , strtotime ("-1 years",strtotime($end_day)));
                }

                $map = [];
                array_push($map,['date','=',$end_day]);

                $baoyou = DB::name('shop_periodicity_log')->where($where)->where($map)->column('by_periodicity_num');
                $baoyou_sum = array_sum($baoyou);

                $last_map = [];
                array_push($last_map,['date','=',$last_end_day]);

                $last_baoyou = DB::name('shop_periodicity_log')->where($where)->where($last_map)->column('by_periodicity_num');
                $last_baoyou_sum = array_sum($last_baoyou);
            }
            array_push($zqx_by_one,$baoyou_sum);
            array_push($last_zqx_by_one,$last_baoyou_sum);
        }
        return ['year'=>[$year,$last_year],'zqx_by_one'=>$zqx_by_one,'last_zqx_by_one'=>$last_zqx_by_one];
    }

    //A类顾客保有率-周期性保有率- 累计保有率  -保有人数分析-周期性保有 - 累计保有  -周期性流失-累计流失
    public function AcustomerRetainRate($shopIds,$request){
        list($shop_type,$market_id,$shop_id,$time_type,$start_time,$end_time) = $this->getPublicSearch($request);
        $shop_where = $where =  [];
        array_push($shop_where,['shop_type','=',$shop_type]);
        array_push($shop_where,['type','<>','2']);
        array_push($shop_where,['status','=','1']);
        if(!empty($market_id)){
            array_push($shop_where,['market_id','=',$market_id]);
        }
        if(!empty($shop_id)){
            array_push($shop_where,['shop_id','=',$shop_id]);
        }
        if(!empty($shopIds)){
            array_push($shop_where,['shop_id','in',$shopIds]);
        }

        $shopIds = ShopModel::where($shop_where)->column('shop_id'); //门店


        $today = date('Ymd');
        $month = date('m');
        $year = date('Y');
        $last_year = $year-1;
        $model = new ReserveandLost();

        $zqx_by_rate = $lj_by_rate = $zqx_by = $lj_by  = $zqx_ls = $lj_ls =  $last_zqx_by = $last_lj_by = $last_zqx_ls = $last_lj_ls = [];
        $public_where = [
            ['shop_id','in',$shopIds],
        ];

        for ($i=1;$i<=12;$i++){
            if($i > $month){
                $zqxby_rete = $ljby_rete =0;
                $last_zqxby_count = $last_ljby_count  = $zqxby_count = $ljby_count = 0;
                $last_zqxls_count = $last_ljls_count  = $zqxls_count = $ljls_count =  0;

            }else{
                $end_day = date('Ymt',strtotime(date('Y-'.$i.'-01')));
                $last_end_day = date ( "Ymd" , strtotime ("-1 years",strtotime($end_day)));

                if($i==$month){
                    $end_day = date('Ymd',strtotime ( "-1 day" ));
                    $last_end_day = date ( "Ymd" , strtotime ("-1 years",strtotime($end_day)));
                }
                $map = [];
                array_push($map,['date','=',$end_day]);
                $lj_data = DB::name('aclass_total_log')->where($public_where)->where($map)->field("sum(by_total_num) as by_total_num,sum(ls_total_num) as ls_total_num")->find();

                $last_map = [];
                array_push($last_map,['date','=',$last_end_day]);
                $last_lj_data = DB::name('aclass_total_log')->where($public_where)->where($last_map)->field("sum(by_total_num) as by_total_num,sum(ls_total_num) as ls_total_num")->find();

                //累计保有-流失
                $last_ljby_count = !empty($last_lj_data['by_total_num'])?$last_lj_data['by_total_num']:0; //累计保有人数
                $last_ljls_count = !empty($last_lj_data['ls_total_num'])?$last_lj_data['ls_total_num']:0; //累计流失人数

                $ljby_count = !empty($lj_data['by_total_num'])?$lj_data['by_total_num']:0; //累计保有人数
                $ljls_count = !empty($lj_data['ls_total_num'])?$lj_data['ls_total_num']:0; //累计流失人数
                $lj_cj_count = bcadd($ljby_count,$ljls_count);
                $ljby_rete = $lj_cj_count >0 ?bcmul(bcdiv($ljby_count,$lj_cj_count,4),100,2):0;  //累计保有率


                $zqx_data = DB::name('aclass_periodicity_log')->where($public_where)->where($map)->field("sum(by_periodicityl_num) as by_periodicityl_num,sum(ls_periodicity_num) as ls_periodicity_num")->find();

                $last_zqx_data = DB::name('aclass_periodicity_log')->where($public_where)->where($last_map)->field("sum(by_periodicityl_num) as by_periodicityl_num,sum(ls_periodicity_num) as ls_periodicity_num")->find();
                //周期性保有-流失
                $last_zqxby_count = !empty($last_zqx_data['by_periodicityl_num'])?$last_zqx_data['by_periodicityl_num']:0; //周期性保有人数
                $last_zqxls_count = !empty($last_zqx_data['ls_periodicity_num'])?$last_zqx_data['ls_periodicity_num']:0;  //周期性保有人数

                $zqxby_count = !empty($zqx_data['by_periodicityl_num'])?$zqx_data['by_periodicityl_num']:0; //周期性保有人数
                $zqxls_count = !empty($zqx_data['ls_periodicity_num'])?$zqx_data['ls_periodicity_num']:0;  //周期性保有人数
                $zqx_cj_count = bcadd($zqxby_count,$zqxls_count);

                $zqxby_rete = $zqx_cj_count > 0 ? bcmul(bcdiv($zqxby_count,$zqx_cj_count,4),100,2):0; //周期性保有率
            }



            array_push($zqx_by_rate,$zqxby_rete);
            array_push($lj_by_rate,$ljby_rete);

            array_push($last_zqx_by,$last_zqxby_count);
            array_push($last_lj_by,$last_ljby_count);
            array_push($zqx_by,$zqxby_count);
            array_push($lj_by,$ljby_count);

            array_push($last_zqx_ls,$last_zqxls_count);
            array_push($last_lj_ls,$last_ljls_count);
            array_push($zqx_ls,$zqxls_count);
            array_push($lj_ls,$ljls_count);

        }
        $return=[
            'year'=>[$year,$last_year],
            'zqx_by_rate'=>$zqx_by_rate,
            'lj_by_rate'=>$lj_by_rate,
            'last_zqx_by'=>$last_zqx_by,
            'last_lj_by'=>$last_lj_by,
            'zqx_by'=>$zqx_by,
            'lj_by'=>$lj_by,
            'last_zqx_ls'=>$last_zqx_ls,
            'last_lj_ls'=>$last_lj_ls,
            'zqx_ls'=>$zqx_ls,
            'lj_ls'=>$lj_ls,
        ];

        return $return;
    }

    //B类顾客保有率-周期性保有率- 周期性保有   累计保有率  - 累计保有  - 周期性流失-累计流失
    public function BcustomerRetainRate($shopIds,$request){
        list($shop_type,$market_id,$shop_id,$time_type,$start_time,$end_time) = $this->getPublicSearch($request);
        $shop_where = $where =  [];
        array_push($shop_where,['shop_type','=',$shop_type]);
        array_push($shop_where,['type','<>','2']);
        array_push($shop_where,['status','=','1']);
        if(!empty($market_id)){
            array_push($shop_where,['market_id','=',$market_id]);
        }
        if(!empty($shop_id)){
            array_push($shop_where,['shop_id','=',$shop_id]);
        }
        if(!empty($shopIds)){
            array_push($shop_where,['shop_id','in',$shopIds]);
        }

        $shopIds = ShopModel::where($shop_where)->column('shop_id'); //门店

        $zqx_by_rate = $lj_by_rate = $zqx_by = $lj_by = $zqx_ls = $lj_ls = $last_zqx_by = $last_lj_by = $last_zqx_ls = $last_lj_ls =  [];
        $year = date('Y');
        $month = date('m');
        $last_year = $year-1;
        for ($i=1;$i<=12;$i++){
            if($i > $month){
                $zqxby_rete = $ljby_rete =0;
                $last_zqxby_count = $last_ljby_count  = $zqxby_count = $ljby_count = 0;
                $last_zqxls_count = $last_ljls_count  = $zqxls_count = $ljls_count =  0;

            }else{

                $end_day = date('Ymt',strtotime(date('Y-'.$i.'-01')));
                $last_end_day = date ( "Ymd" , strtotime ("-1 years",strtotime($end_day)));

                if($i==$month){
                    $end_day = date('Ymd',strtotime ( "-1 day" ));
                    $last_end_day = date ( "Ymd" , strtotime ("-1 years",strtotime($end_day)));
                }

                $public_map = [
                    ['shop_id','in',$shopIds],
                ];

                $map =[];
                array_push($map,['date','=',$end_day]);
                $lj_data = DB::name('bclass_total_log')->where($public_map)->where($map)->field("sum(by_total_num) as by_total_num,sum(ls_total_num) as ls_total_num")->find();

                $last_map =[];
                array_push($last_map,['date','=',$last_end_day]);
                $last_lj_data = DB::name('bclass_total_log')->where($public_map)->where($last_map)->field("sum(by_total_num) as by_total_num,sum(ls_total_num) as ls_total_num")->find();


                //累计保有-流失
                $last_ljby_count = !empty($last_lj_data['by_total_num'])?$last_lj_data['by_total_num']:0; //累计保有人数
                $last_ljls_count = !empty($last_lj_data['ls_total_num'])?$last_lj_data['ls_total_num']:0; //累计流失人数

                $ljby_count = !empty($lj_data['by_total_num'])?$lj_data['by_total_num']:0; //累计保有人数
                $ljls_count = !empty($lj_data['ls_total_num'])?$lj_data['ls_total_num']:0; //累计流失人数
                $lj_cj_count = bcadd($ljby_count,$ljls_count);
                $ljby_rete = $lj_cj_count >0 ?bcmul(bcdiv($ljby_count,$lj_cj_count,4),100,2):0;  //累计保有率

                $zqx_data = DB::name('bclass_periodicity_log')->where($public_map)->where($map)->field("sum(by_periodicityl_num) as by_periodicityl_num,sum(ls_periodicity_num) as ls_periodicity_num")->find();

                $last_zqx_data = DB::name('bclass_periodicity_log')->where($public_map)->where($last_map)->field("sum(by_periodicityl_num) as by_periodicityl_num,sum(ls_periodicity_num) as ls_periodicity_num")->find();

                //周期性保有-流失
                $last_zqxby_count = !empty($last_zqx_data['by_periodicityl_num'])?$last_zqx_data['by_periodicityl_num']:0; //周期性保有人数
                $last_zqxls_count = !empty($last_zqx_data['ls_periodicity_num'])?$last_zqx_data['ls_periodicity_num']:0;  //周期性保有人数

                $zqxby_count = !empty($zqx_data['by_periodicityl_num'])?$zqx_data['by_periodicityl_num']:0; //周期性保有人数
                $zqxls_count = !empty($zqx_data['ls_periodicity_num'])?$zqx_data['ls_periodicity_num']:0;  //周期性保有人数
                $zqx_cj_count = bcadd($zqxby_count,$zqxls_count);

                $zqxby_rete = $zqx_cj_count > 0 ? bcmul(bcdiv($zqxby_count,$zqx_cj_count,4),100,2):0; //周期性保有率
            }

            array_push($zqx_by_rate,$zqxby_rete);
            array_push($lj_by_rate,$ljby_rete);
            array_push($last_zqx_by,$last_zqxby_count);
            array_push($last_lj_by,$last_ljby_count);
            array_push($zqx_by,$zqxby_count);
            array_push($lj_by,$ljby_count);
            array_push($last_zqx_ls,$last_zqxls_count);
            array_push($last_lj_ls,$last_ljls_count);
            array_push($zqx_ls,$zqxls_count);
            array_push($lj_ls,$ljls_count);
        }


        $return = [
            'year'=>[$year,$last_year],
            'zqx_by_rate'=>$zqx_by_rate,
            'lj_by_rate'=>$lj_by_rate,
            'last_zqx_by'=>$last_zqx_by,
            'last_lj_by'=>$last_lj_by,
            'zqx_by'=>$zqx_by,
            'lj_by'=>$lj_by,
            'last_zqx_ls'=>$last_zqx_ls,
            'last_lj_ls'=>$last_lj_ls,
            'zqx_ls'=>$zqx_ls,
            'lj_ls'=>$lj_ls,
        ];

        return $return;
    }



}
